Get the Index of the Max value in an Array in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 09 20212 min read

Get the Index of the Max value in an Array #

To get the index of the max value in an array:

  1. Get the max value in the array, using the Math.max() method.
  2. Call the indexOf() method on the array, passing it the max value.
  3. The indexOf method returns the index of the first occurrence of the value in the array or -1 if the value is not found.
index.js
const arr = [3, 5, 8, 100, 20]; const max = Math.max(...arr); const index = arr.indexOf(max); console.log(index); // ๐Ÿ‘‰๏ธ 3

We use the Math.max method to get the max value in the array.

Since the Math.max method expects multiple, comma-separated numbers as arguments, we can't just pass it the array directly.

index.js
const max = Math.max(3, 5, 8) console.log(max) // ๐Ÿ‘‰๏ธ 8

We use the spread operator (...) to unpack the values from the array and pass them as multiple, comma-separated arguments to the Math.max method.

The last step is to get the index of the last value, by using the Array.indexOf method.

The Spread operator is not supported in Internet Explorer, if you need to support the browser use the apply method instead.
index.js
// Supported in Internet Explorer const arr = [3, 5, 8, 100, 20, 100]; // ๐Ÿ‘‡๏ธ using apply const max = Math.max.apply(null, arr); const index = arr.indexOf(max); console.log(index); // ๐Ÿ‘‰๏ธ 3

The arguments we passed to the Function.apply method are:

  1. the this argument - for our purposes it's irrelevant
  2. the array, whose values will get unpacked and passed to the Math.max method as multiple, comma-separated arguments

If we had multiple array elements with the same max value, the indexOf method would return only the index of the first occurrence.

If you need to get the indexes of all elements with the max value in the array, use this approach instead.
index.js
const arr = [3, 5, 8, 100, 20, 100]; const max = Math.max(...arr); const indexes = []; for (let index = 0; index < arr.length; index++) { if (arr[index] === max) { indexes.push(index); } } console.log(indexes) // ๐Ÿ‘‰๏ธ [3, 5]

In the example we use a for loop to iterate for array.length iterations.

On each iteration, we check if the element at that index is the max value, if it is, we push the current index to the indexes array.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee