Get The Index Of The Min Value In An Array In JavaScript

To get the index of the min value in an array in JavaScript, use the Math.min() method and the indexOf() method. The Math.min() method returns the smallest of zero or more numbers. The indexOf() method returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

get the index of the min value in an array in javascript

Get The Index Of The Min Value In An Array In JavaScript

The Math.min() method returns the smallest of zero or more numbers. The indexOf() method returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

Example

In this example, we have an array of numbers, and we use the Math.min() method to get the min value in the array. We then use the indexOf() method to get the index of that min value.

var arr = [-5, 10, -3, 12, -9, 5, 90, 0];

var min = Math.min(...arr); //-9

console.log(min);

var index = arr.indexOf(min); //4

console.log(index);

Note that we have used the spread operator (…) inside the Math.min() method. The Math.min() method expects numbers as arguments. The spread operator expands the arr array and passes its elements as individual arguments to the Math.min() method.

Alternatively, we could use the apply() method with Math.min(), for Internet Explorer support.

var arr = [-5, 10, -3, 12, -9, 5, 90, 0];

var min = Math.min.apply(null, arr); //-9

console.log(min);

var index = arr.indexOf(min); //4

console.log(index);

In the above example, we have used the apply() method to call the Math.min() method. The first argument passed to the apply() method is the `this` value. In our case, since we are not using `this` inside Math.min(), we have passed null as the first argument.

The second argument is an array of numbers.

The apply() method expands the array and passes its element as individual arguments to the Math.min() method.

If you are using a modern browser that supports the spread operator, it is recommended to use the spread operator instead of apply().

The Math.min() method returns the smallest of zero or more numbers. The indexOf() method returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

Conclusion

In this article, we looked at how to get the index of the min value in an array in JavaScript. We saw how to use the Math.min() method and the indexOf() method to achieve this.

We also looked at how to use the spread operator and the apply() method with Math.min(). If you are using a modern browser that supports the spread operator, it is recommended to use the spread operator instead of apply().

Leave a Reply