Sat Oct 09 2021·2 min read
Photo by Brooke Cagle
To get the index of the min value in an array:
indexOf()method on the array, passing it the min value.
indexOfmethod returns the index of the first occurrence of the value in the array or
-1if 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
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
Then, we find the index of the first occurrence of the
min value by calling
If we had multiple array elements with the value of
would return the index of the first occurrence.
...is not supported in Internet Explorer. If you need to support the browser, use the
applymethod to get the
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:
thisargument - for our purposes it's irrelevant
Math.minmethod as multiple, comma-separated arguments
applymethod unpacks the values from the array and passes them as multiple arguments to the function you call it on.
I'll send you 1 email a week with links to all of the articles I've written that week