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

avatar

Borislav Hadzhiev

Sat Oct 09 20212 min read

banner

Photo by Brooke Cagle

Get the Index of the Min value in an Array in JavaScript #

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

  1. Get the min value in the array, using the Math.min() method.
  2. Call the indexOf() method on the array, passing it the min 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 = [10, 5, 0, 15, 30]; const min = Math.min(...arr); const index = arr.indexOf(min); console.log(index); // ๐Ÿ‘‰๏ธ 2

We use the spread operator ... when calling the Math.min method.

Since the Math.min method expects comma separated numbers as arguments, we can't directly pass it an array.

index.js
const min = Math.min(10, 5, 0) console.log(min) // ๐Ÿ‘‰๏ธ 0

We use the ... operator to unpack the values of the array and pass them as multiple comma-separated arguments to the Math.min method.

Then, we find the index of the first occurrence of the min value by calling the Array.indexOf method.

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

The spread operator ... is not supported in Internet Explorer. If you need to support the browser, use the apply method to get the min value instead.
index.js
const arr = [10, 5, 0, 15, 30]; // ๐Ÿ‘‡๏ธ now using apply, instead of ... const min = Math.min.apply(null, arr); const index = arr.indexOf(min); console.log(index); // ๐Ÿ‘‰๏ธ 2

The only difference in the code is how we get the min value in the array.

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

  1. the this argument - for our purposes it's irrelevant
  2. the array, whose values will be passed to the Math.min method as multiple, comma-separated arguments
Under the hood the apply method unpacks the values from the array and passes them as multiple arguments to the function you call it on.

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