Use the Array.prototype.indexOf and Math.max Methods
Math.max and the array’s
For instance, we can write:
const arr = [0, 21, 22, 7]; const index = arr.indexOf(Math.max(...arr)); console.log(index)
Math.max with the elements of
arr in as arguments by spreading
arr into the
This returns the greatest element in
And then we can call
arr.indexOf on the greatest element of
index is 2, which is the index of value 22 in
Use the Array.prototype.reduce Method
To use it, we write:
const arr = [0, 21, 22, 7]; const index = arr.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0); console.log(index)
arr with a callback that has the
iMax parameter, which is the index of the greatest value of
arr so far.
x is the entry of
arr being iterated through.
i is the index of
arr is the
arr array itself.
We return the index of the greatest element by checking if
x is bigger than the current element being recorded as the largest so bar, which is
x is bigger than
arr[iMax] , we return
Otherwise, we return
0 is the initial value of the index of the greatest element of
index is 2 as we saw in the previous example.
We can use the