Reputation: 1375
I know that you can have the minimum value of an array by typing
var min = Math.min.apply(null, array)
but this will return the smallest value of an array and not the id of this one for exemple if I have these values:
array[1] = 24;
array[2] = 45;
I want it to return 1 (the ID holding the minimum value) but idk how to do, could someone help me with this issue please?
Upvotes: 0
Views: 1700
Reputation: 3662
You can do it like this:
var id = array.indexOf(Math.min.apply(null, array));
Upvotes: 2
Reputation: 3543
You can use Array#reduce()
to get the smallest number, while avoiding holes in the Array if needed.
array.reduce(function(obj, n, i) {
if (n < obj.min)
obj.i = i;
return obj;
}, {min:Infinity,i:-1}).i;
Or if performance and compatibility is a concern, you could just loop.
var res = -1;
var min = Infinity;
for (var i = 0; i < array.length; i++) {
if ((i in array) && array[i] < min) {
min = array[i];
res = i;
}
}
Upvotes: 3
Reputation: 1264
Just like the algorithm for finding the min value, but you have to track the minimum index as well
function minIndex(arr) {
if (!arr || arr.length === 0) {
return -1;
}
var min = arr[0];
var minIndex = 0;
for (var len = arr.length; len > 0; len--) {
if (arr[len] < min) {
min = arr[len];
minIndex = len;
}
}
return minIndex;
}
check out this fiddle
Upvotes: 0
Reputation: 19679
Once you've got the value, you can use indexOf
to get the index, like this:
var index = array.indexOf(Math.min.apply(null, array));
You should be aware that indexOf
was only recently included in JavaScript (ES5/JS 1.6 to be precise) so you may want to find some wrapper for it if the function does not exist.
See the MDN for more information (which contains an example implementation of a backwards compatible function).
Upvotes: 0
Reputation: 19738
var index = array.indexOf(Math.min.apply(null, array));
Upvotes: 4