简体   繁体   中英

how do I find the id of the minimum value of an array?

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?

var index = array.indexOf(Math.min.apply(null, array));

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;
    }
}

您可以这样做:

var id = array.indexOf(Math.min.apply(null, array));

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM