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

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

    I'd like to explain the terse accepted answer step-by-step:

    var objects = [{ x: 3 }, { x: 1 }, { x: 2 }];
    
    // array.map lets you extract an array of attribute values
    var xValues = objects.map(function(o) { return o.x; });
    // es6
    xValues = Array.from(objects, o => o.x);
    
    // function.apply lets you expand an array argument as individual arguments
    // So the following is equivalent to Math.max(3, 1, 2)
    // The first argument is "this" but since Math.max doesn't need it, null is fine
    var xMax = Math.max.apply(null, xValues);
    // es6
    xMax = Math.max(...xValues);
    
    // Finally, to find the object that has the maximum x value (note that result is array):
    var maxXObjects = objects.filter(function(o) { return o.x === xMax; });
    
    // Altogether
    xMax = Math.max.apply(null, objects.map(function(o) { return o.x; }));
    var maxXObject = objects.filter(function(o) { return o.x === xMax; })[0];
    // es6
    xMax = Math.max(...Array.from(objects, o => o.x));
    maxXObject = objects.find(o => o.x === xMax);
    
    
    document.write('<p>objects: ' + JSON.stringify(objects) + '</p>');
    document.write('<p>xValues: ' + JSON.stringify(xValues) + '</p>');
    document.write('<p>xMax: ' + JSON.stringify(xMax) + '</p>');
    document.write('<p>maxXObjects: ' + JSON.stringify(maxXObjects) + '</p>');
    document.write('<p>maxXObject: ' + JSON.stringify(maxXObject) + '</p>');

    Further information:

    • Math.max.apply()
    • Array.prototype.map()
    • Array.from()
    • Function.prototype.apply()
    • Array.prototype.filter()
    • Array.prototype.find()
    0 讨论(0)
  • 2020-11-22 08:28

    if you (or, someone here) are free to use lodash utility library, it has a maxBy function which would be very handy in your case.

    hence you can use as such:

    _.maxBy(jsonSlice, 'y');
    
    0 讨论(0)
  • 2020-11-22 08:31

    To find the maximum y value of the objects in array:

    Math.max.apply(Math, array.map(function(o) { return o.y; }))
    
    0 讨论(0)
  • 2020-11-22 08:32

    ES6 solution

    Math.max(...array.map(function(o){return o.y;}))

    For more details see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

    0 讨论(0)
  • 2020-11-22 08:37

    Or a simple sort! Keeping it real :)

    array.sort((a,b)=>a.y<b.y)[0].y
    
    0 讨论(0)
  • 2020-11-22 08:39
    var max = 0;                
    jQuery.map(arr, function (obj) {
      if (obj.attr > max)
        max = obj.attr;
    });
    
    0 讨论(0)
提交回复
热议问题