Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find indexes of multiple max values in array

I have an example array:

var arr = [10, 67, 100, 100];

I want to find the indexes of the maximum values in the array.

This function finds only one index:

function max(arr) {
      var max = arr[0];
      var maxIndex = 0;
      for (var i = 1; i < arr.length; i++) {
          if (arr[i] > max) {
              maxIndex = i;
              max = arr[i];
          }
      }
      return maxIndex;
 }

How can I modify it to return an array of max indexes? In the example array above, it should return

[2, 3].

like image 953
frosty Avatar asked Jun 12 '16 23:06

frosty


3 Answers

Instead of keeping track of just one index, you'll need to keep track of all indices. Give this a try:

function max(arr) {
    var max = -Infinity;
    var maxIndices = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === max) {
          maxIndices.push(i);
        } else if (arr[i] > max) {
            maxIndices = [i];
            max = arr[i];
        }
    }
    return maxIndices;
 }
like image 167
user94559 Avatar answered Sep 22 '22 17:09

user94559


I would do like this;

var arr = [10, 67, 100, 100],
      m = Math.max(...arr),
  maxes = arr.reduce((p,c,i,a) => c ==  m ? p.concat(i) : p,[]);
console.log(maxes);
like image 28
Redu Avatar answered Sep 22 '22 17:09

Redu


function max(arr) {
    var largest = Math.max.apply(Math, arr);

    var indexes = [], i = -1;
    while ((i = arr.indexOf(largest, i+1)) != -1){
        indexes.push(i);
    }
    return indexes;
}

var arr = [10, 67, 100, 100];
console.log(max(arr));
like image 21
Midas Avatar answered Sep 21 '22 17:09

Midas