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

Last updated: Aug 23, 2022

Photo from Unsplash

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

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

1. Use the `Math.min()` method to get the min value in the array.
2. Use the `Array.indexOf()` method to get the index of the min value.
3. The `indexOf` method returns the index of the first occurrence of the value in the array.
index.js
```Copied!```const arr = [10, 5, 0, 15, 30];

const min = Math.min(...arr);

const index = arr.indexOf(min);
console.log(index); // 👉️ 2
``````

We used the spread (...) operator when we called the Math.min method.

The `Math.min` method expects comma-separated numbers as arguments, so we can't directly pass it an array.
index.js
```Copied!```const min = Math.min(10, 5, 0)
console.log(min) // 👉️ 0
``````

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

We used the Array.indexOf method to find the index of the first occurrence of the `min` value.

index.js
```Copied!```const arr = [10, 5, 0, 15, 30];

const min = Math.min(...arr);

const index = arr.indexOf(min);
console.log(index); // 👉️ 2
``````
If there were multiple array elements with the value of `0`, the `indexOf` method would return the index of the first occurrence.

You can also use the `Function.apply` method as an alternative to the spread (...) operator.

index.js
```Copied!```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 passed 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 of the array and passes them as multiple arguments to the function the method is called on.