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:
xxxxxxxxxx
1
var numbers = [2, 3, 1]
2
3
var indexOfMax = numbers.indexOf(Math.max(numbers));
4
5
console.log(indexOfMax); // 1
Note:
This solution is not optimal.
In this example, we present a reusable function that also works in older web browsers.
xxxxxxxxxx
1
function indexOfMax(array) {
2
if (array.length === 0) {
3
return -1;
4
}
5
6
var max = array[0];
7
var result = 0;
8
9
for (var i = 1; i < array.length; ++i) {
10
if (array[i] > max) {
11
result = i;
12
max = array[i];
13
}
14
}
15
16
return result;
17
}
18
19
20
// Usage example:
21
22
var numbers = [2, 3, 1];
23
24
var maxIndex = indexOfMax(numbers);
25
26
console.log(maxIndex); // 1