EN
JavaScript - get index of greatest value in array
0
points
In this article, we would like to show you how to get the index of the greatest value in an array in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
var numbers = [2, 3, 1]
var indexOfMax = numbers.indexOf(Math.max(...numbers));
console.log(indexOfMax); // 1
Note:
This solution is not optimal.
Practical example
In this example, we present a reusable function that also works in older web browsers.
// ONLINE-RUNNER:browser;
function indexOfMax(array) {
if (array.length === 0) {
return -1;
}
var max = array[0];
var result = 0;
for (var i = 1; i < array.length; ++i) {
if (array[i] > max) {
result = i;
max = array[i];
}
}
return result;
}
// Usage example:
var numbers = [2, 3, 1];
var maxIndex = indexOfMax(numbers);
console.log(maxIndex); // 1