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

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 used the Math.max method to get the max value in the array.

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

index.js
const max = Math.max(3, 5, 8) console.log(max) // 👉️ 8

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

index.js
const arr = [3, 5, 8, 100, 20]; const max = Math.max(...arr); const index = arr.indexOf(max); console.log(index); // 👉️ 3

The last step is to use the Array.indexOf method to get the index of the max value.

The Spread operator is not supported in Internet Explorer. If you need to support the browser use the apply method instead.
index.js
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.

Get the indexes of all elements with the max value in an array #

To get the indexes of all elements with the max value in an array:

  1. Use the Math.max() method to get the max value in the array.
  2. Declare an indexes variable that stores an empty array.
  3. Iterate over the array and push only the indexes of the max values to the indexes array.
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]

We used a for loop to iterate for array.length iterations.

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

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.