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]
.
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;
}
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);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With