在对象数组中查找属性的最大值

廉价感情. 提交于 2020-03-06 11:25:23

我正在寻找一种非常快速,干净且有效的方法来获取以下JSON切片中的最大“ y”值:

[
  {
    "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
  }
]

for-loop是解决此问题的唯一方法吗? 我热衷于使用Math.max


#1楼

var max = 0;                
jQuery.map(arr, function (obj) {
  if (obj.attr > max)
    max = obj.attr;
});

#2楼

在对象数组中找到属性“ Y”具有最大值的对象

一种方法是使用Array reduce ..

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

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce(IE9及更高版本)

如果您不需要支持IE(仅Edge),或者可以使用Babel等预编译器,则可以使用更简洁的语法。

const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)

#3楼

简洁的ES6(Babel)

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

如果arrayToSearchIn为空,则第二个参数应确保默认值。


#4楼

我想逐步解释简短的答案

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 ox; }); // es6 xValues = Array.from(objects, o => ox); // 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 ox === xMax; }); // Altogether xMax = Math.max.apply(null, objects.map(function(o) { return ox; })); var maxXObject = objects.filter(function(o) { return ox === xMax; })[0]; // es6 xMax = Math.max(...Array.from(objects, o => ox)); maxXObject = objects.find(o => ox === 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>');

更多信息:


#5楼

如果您(或这里的某人)可以自由使用lodash实用程序库,则它具有maxBy函数,在您的情况下非常方便。

因此您可以这样使用:

_.maxBy(jsonSlice, 'y');
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!