Return index of greatest value in an array Return index of greatest value in an array arrays arrays

Return index of greatest value in an array


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.


In one line and probably faster then arr.indexOf(Math.max.apply(Math, arr)):

var a = [0, 21, 22, 7];var indexOfMaxValue = a.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);document.write("indexOfMaxValue = " + indexOfMaxValue); // prints "indexOfMaxValue = 2"