Get the Index of Min value of an Array in JavaScript
In this tutorial, we are going to learn about how to get the index of the Minimum value from an array using the JavaScript.
Get the Index of Min Value of an Array
To get the index of Min value of an array, we can use the combination of Math.Min() and Array.IndexOf() methods.
The Math.Min() method takes the array of elements as a argument and returns the Min value from the array.
The Array.indexOf() method takes the element as a argument and returns the index of it.
Here is an example:
const arr = [22, 4, 55, 34, 12];
const MinNumber = Math.Min(...arr);
const result = arr.indexOf(MinNumber);
console.log(result);
Output:
1 // index
In the example above, we have used the Math.Min(..arr)
method to get the Min value of an array, then we have passed the Min value to the
Array.indexOf() method to get index of it.
The Math.Min() method accepts only the individual values but not an array, so we unpacked the array by using the es6 (…) spread operator and passed to it.
We can also modified the above code in the single line like this :
const arr = [22, 4, 55, 34, 12];
const result = arr.indexOf(Math.Min(...arr));
console.log(result); // 1