Find the min/max element of an Array in JavaScript

前端 未结 30 2127
無奈伤痛
無奈伤痛 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:39

    If you use the library sugar.js, you can write arr.min() and arr.max() as you suggest. You can also get min and max values from non-numeric arrays.

    min( map , all = false ) Returns the element in the array with the lowest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all min values in an array.

    max( map , all = false ) Returns the element in the array with the greatest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all max values in an array.

    Examples:

    [1,2,3].min() == 1
    ['fee','fo','fum'].min('length') == "fo"
    ['fee','fo','fum'].min('length', true) == ["fo"]
    ['fee','fo','fum'].min(function(n) { return n.length; }); == "fo"
    [{a:3,a:2}].min(function(n) { return n['a']; }) == {"a":2}
    ['fee','fo','fum'].max('length', true) == ["fee","fum"]
    

    Libraries like Lo-Dash and underscore.js also provide similar powerful min and max functions:

    Example from Lo-Dash:

    _.max([4, 2, 8, 6]) == 8
    var characters = [
      { 'name': 'barney', 'age': 36 },
      { 'name': 'fred',   'age': 40 }
    ];
    _.max(characters, function(chr) { return chr.age; }) == { 'name': 'fred', 'age': 40 }
    

提交回复
热议问题