frosty frosty - 5 months ago 13
Javascript Question

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]
.

Answer

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;
 }
Comments