Find the min/max element of an Array in JavaScript

前端 未结 30 2058
無奈伤痛
無奈伤痛 2020-11-21 06:18

How can I easily obtain the min or max element of a JavaScript Array?

Example Psuedocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max()         


        
30条回答
  •  感动是毒
    2020-11-21 06:51

    A simple solution to find the minimum value over an Array of elements is to use the Array prototype function reduce:

    A = [4,3,-9,-2,2,1];
    A.reduce((min, val) => val < min ? val : min, A[0]); // returns -9
    

    or using JavaScript's built-in Math.Min() function (thanks @Tenflex):

    A.reduce((min,val) => Math.min(min,val), A[0]);
    

    This sets min to A[0], and then checks for A[1]...A[n] whether it is strictly less than the current min. If A[i] < min then min is updated to A[i]. When all array elements has been processed, min is returned as the result.

    EDIT: Include position of minimum value:

    A = [4,3,-9,-2,2,1];
    A.reduce((min, val) => val < min._min ? {_min: val, _idx: min._curr, _curr: min._curr + 1} : {_min: min._min, _idx: min._idx, _curr: min._curr + 1}, {_min: A[0], _idx: 0, _curr: 0}); // returns { _min: -9, _idx: 2, _curr: 6 }
    

提交回复
热议问题