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

前端 未结 13 2252
不思量自难忘°
不思量自难忘° 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('

    objects: ' + JSON.stringify(objects) + '

    '); document.write('

    xValues: ' + JSON.stringify(xValues) + '

    '); document.write('

    xMax: ' + JSON.stringify(xMax) + '

    '); document.write('

    maxXObjects: ' + JSON.stringify(maxXObjects) + '

    '); document.write('

    maxXObject: ' + JSON.stringify(maxXObject) + '

    ');

    Further information:

    • Math.max.apply()
    • Array.prototype.map()
    • Array.from()
    • Function.prototype.apply()
    • Array.prototype.filter()
    • Array.prototype.find()

提交回复
热议问题