Borislav Hadzhiev
Sat Oct 09 2021·2 min read
Photo by Brooke Cagle
To get the index of the min value in an array:
Math.min()
method.indexOf()
method on the array, passing it the min value.indexOf
method returns the index of the first occurrence of the value
in the array or -1
if the value is not found.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.
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.
...
is not supported in Internet Explorer. If you need to support the browser, use the apply
method to get the min
value instead.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:
this
argument - for our purposes it's irrelevantMath.min
method as multiple,
comma-separated argumentsapply
method unpacks the values from the array and passes them as multiple arguments to the function you call it on.