15 January 2024

You have an original array and another array where the elements are grouped in threes. You want to find the group in the second array that corresponds to a given element from the original array.

Source code viewer
  1. const originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  2. const groupedArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
  3.  
  4. // Assuming you want to find the group for the element 4 from the original array
  5. const elementToFind = 4;
  6.  
  7. // Find the index of the element in the original array
  8. const elementIndex = originalArray.indexOf(elementToFind);
  9.  
  10. // Calculate the corresponding group index
  11. const groupIndex = Math.floor(elementIndex / 3);
  12.  
  13. // Get the corresponding group from the grouped array
  14. const correspondingGroup = groupedArray[groupIndex];
  15.  
  16. console.log("Original Array:", originalArray);
  17. console.log("Grouped Array:", groupedArray);
  18. console.log(`Corresponding Group for ${elementToFind}:`, correspondingGroup);
Programming Language: ECMAScript