1. If you only want the first instance:
var arrayMaxIndex = function(array) {
return array.indexOf(Math.max.apply(null, array));
};
console.log(arrayMaxIndex([1,2,7,2])); //outputs 2
2. If you want all occurrences of the max:
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes;
}
var arrayAllMaxIndexes = function(array){
return getAllIndexes(array, Math.max.apply(null, array));
}
console.log(arrayAllMaxIndexes([1,2,7,2,7])); // outputs [2,4]
Everyone does ES6 Updates so here is mine:
const arr = [1, 2, 3];
const max = Math.max.apply(Math, arr.map((i) => i));
const maxIndex = arr.indexOf(max);
Also you can achieve the same thing using reduce
:
const getMax = (arr) => arr.reduce((acc, item) => (item > acc ? item : acc), arr[0]);