Find the min/max element of an Array in JavaScript

前端 未结 30 2659
無奈伤痛
無奈伤痛 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:49

    Here's one way to get the max value from an array of objects. Create a copy (with slice), then sort the copy in descending order and grab the first item.

    var myArray = [
        {"ID": 1, "Cost": 200},
        {"ID": 2, "Cost": 1000},
        {"ID": 3, "Cost": 50},
        {"ID": 4, "Cost": 500}
    ]
    
    maxsort = myArray.slice(0).sort(function(a, b) { return b.ID - a.ID })[0].ID; 
    

提交回复
热议问题