Return indexes of greatest values in an array in JavaScript


We are required to write a JavaScript function that takes in an array of Numbers. The array may contain more than one greatest element (i.e., repeating greatest element).

We are required to write a JavaScript function that takes in one such array and returns all the indices of the greatest element.

Example

The code for this will be −

const arr = [10, 5, 4, 10, 5, 10, 6];
const findGreatestIndices = arr => {
   const val = Math.max(...arr);
   const greatest = arr.reduce((indexes, element, index) => {
      if(element === val){
         return indexes.concat([index]);
      } else {
         return indexes;
      };
   }, []);
   return greatest;
}
console.log(findGreatestIndices(arr));

Output

And the output in the console will be −

[ 0, 3, 5 ]

Updated on: 20-Nov-2020

266 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements