Finding the max value of an attribute in an array of objects

前端 未结 13 2130
不思量自难忘°
不思量自难忘° 2020-11-22 08:05

I\'m looking for a really quick, clean and efficient way to get the max \"y\" value in the following JSON slice:

[
  {
    \"x\": \"8/11/2009\",
    \"y\": 0         


        
13条回答
  •  臣服心动
    2020-11-22 08:23

    // Here is very simple way to go:
    
    // Your DataSet.
    
    let numberArray = [
      {
        "x": "8/11/2009",
        "y": 0.026572007
      },
      {
        "x": "8/12/2009",
        "y": 0.025057454
      },
      {
        "x": "8/13/2009",
        "y": 0.024530916
      },
      {
        "x": "8/14/2009",
        "y": 0.031004457
      }
    ]
    
    // 1. First create Array, containing all the value of Y
    let result = numberArray.map((y) => y)
    console.log(result) // >> [0.026572007,0.025057454,0.024530916,0.031004457]
    
    // 2.
    let maxValue = Math.max.apply(null, result)
    console.log(maxValue) // >> 0.031004457
    

提交回复
热议问题