我正在寻找一种非常快速,干净且有效的方法来获取以下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
如果您不需要支持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('
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) + '
');更多信息:
#5楼
如果您(或这里的某人)可以自由使用lodash实用程序库,则它具有
因此您可以这样使用:
_.maxBy(jsonSlice, 'y');