I have this:
JavaScript
x
2
1
var arr = [0, 21, 22, 7];
2
What’s the best way to return the index of the highest value into another variable?
Advertisement
Answer
This is probably the best way, since it’s reliable and works on old browsers:
JavaScript
1
18
18
1
function indexOfMax(arr) {
2
if (arr.length === 0) {
3
return -1;
4
}
5
6
var max = arr[0];
7
var maxIndex = 0;
8
9
for (var i = 1; i < arr.length; i++) {
10
if (arr[i] > max) {
11
maxIndex = i;
12
max = arr[i];
13
}
14
}
15
16
return maxIndex;
17
}
18
There’s also this one-liner:
JavaScript
1
2
1
let i = arr.indexOf(Math.max(arr));
2
It performs twice as many comparisons as necessary and will throw a RangeError
on large arrays, though. I’d stick to the function.