0

I would like to find the most concise way to find the index of the largest number in an array. Example: var array = [0,6,7,7,7];
The function should return [2,3,4]

Note: it is not the same as Return index of greatest value in an array Why? There the answers return only one of the largest. e.g var array = [0,6,7,7,7] would return 2 or 4.

Update: Quite a few people have marked this as a duplicate question. IT IS NOT! I explained the difference in the note above. Where is the supposed answer to what I am asking in Return index of greatest value in an array
I am also disheartened by the fact my first question was down voted almost immediately.

Update: Found another answer at Return index of greatest value in an array

Community
  • 1
  • 1
codeman
  • 115
  • 6

3 Answers3

1
function findLargestOccurances(){
  //Sort the initial array to make it easier
  var arr = [0,6,7,7,7].sort();
  //The largest element is always at the end
  var largest = arr[arr.length-1];
  //The return array will hold positions of the largest element in the array
  var retArr = [];
  //Find occurances of the largest # in the array
  arr.forEach(function(ele,idx){
    //If the current element is the largest one, record the occurance index
    if (ele === largest)
      retArr.push(idx);
  });
  //Log the return array, open your browsers console to see the result!
  console.log(retArr);
}

findLargestOccurances();

This function will work for jumbled elements also! I've created a code pen here:

http://codepen.io/ShashankaNataraj/pen/WwENLb?editors=1011

shashanka n
  • 2,568
  • 1
  • 14
  • 21
0

This is so close to Return index of greatest value in an array.

But if you want to get all indexes, you can just iterate the array, pushing the current index to an argmax array when the current item is equal to max, the maximum number found until the moment; or update max and argmax when you find a greater item.

var max = -Infinity, argmax = [];
for(var i=0; i<array.length; ++i)
  if(array[i] > max) max = array[i], argmax = [i];
  else if(array[i] === max) argmax.push(i);
argmax; // [2,3,4]
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

Try the code below. It will give you the required output

 var array1=[0,6,7,7,7]; 
 var array2=[]; 
 var i = Math.max.apply(Math, array1);
     
     for (var x = 0; x < array1.length; x++) {
           
           if (array1[x] == i) {
              
                 array2.push(x);               
                 
           }
        }
    
    var z = array2.toString();
    var_dump(z);                                   
                                       
Webdev
  • 617
  • 6
  • 24