I have this:
var arr = [0, 21, 22, 7];
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:
function indexOfMax(arr) { if (arr.length === 0) { return -1; } 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; }
There’s also this one-liner:
let i = arr.indexOf(Math.max(...arr));
It performs twice as many comparisons as necessary and will throw a RangeError
on large arrays, though. I’d stick to the function.