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

前端 未结 13 2122
不思量自难忘°
不思量自难忘° 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:18

    Well, first you should parse the JSON string, so that you can easily access it's members:

    var arr = $.parseJSON(str);
    

    Use the map method to extract the values:

    arr = $.map(arr, function(o){ return o.y; });
    

    Then you can use the array in the max method:

    var highest = Math.max.apply(this,arr);
    

    Or as a one-liner:

    var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));
    
    0 讨论(0)
  • 2020-11-22 08:20

    Find the object whose property "Y" has the greatest value in an array of objects

    One way would be to use Array reduce..

    const max = data.reduce(function(prev, current) {
        return (prev.y > current.y) ? prev : current
    }) //returns object
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce (IE9 and above)

    If you don't need to support IE (only Edge), or can use a pre-compiler such as Babel you could use the more terse syntax.

    const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
    
    0 讨论(0)
  • 2020-11-22 08:23

    Here is the shortest solution (One Liner) ES6:

    Math.max(...values.map(o => o.y));
    
    0 讨论(0)
  • 2020-11-22 08:23

    Each array and get max value with Math.

    data.reduce((max, b) => Math.max(max, b.costo), data[0].costo);
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 08:26

    clean and simple ES6 (Babel)

    const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);
    

    The second parameter should ensure a default value if arrayToSearchIn is empty.

    0 讨论(0)
提交回复
热议问题