Javascript 在对象数组中查找属性的最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4020796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the max value of an attribute in an array of objects
提问by Rio
I'm looking for a really quick, clean and efficient way to get the max "y" value in the following JSON slice:
我正在寻找一种非常快速、干净和有效的方法来获取以下 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
}
]
Is a for-loop the only way to go about it? I'm keen on somehow using Math.max
.
for 循环是唯一的方法吗?我热衷于以某种方式使用Math.max
.
回答by tobyodavies
To find the maximum y
value of the objects in array
:
要找到y
中对象的最大值array
:
Math.max.apply(Math, array.map(function(o) { return o.y; }))
回答by Andy Polhill
Find the object whose property "Y" has the greatest value in an array of objects
在对象数组中查找属性“Y”具有最大值的对象
One way would be to use Array reduce..
一种方法是使用 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/Reducehttp://caniuse.com/#search=reduce(IE9 and above)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce(IE9及以上)
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.
如果您不需要支持 IE(仅 Edge),或者可以使用 Babel 等预编译器,则可以使用更简洁的语法。
const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
回答by Vitaliy Kotov
clean and simple ES6 (Babel)
干净简单的 ES6 (Babel)
const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);
The second parameter should ensure a default value if arrayToSearchIn
is empty.
如果arrayToSearchIn
为空,则第二个参数应确保默认值。
回答by Kamil Kie?czewski
Comparison of tree ONELINERSwhich handle minus numbers case (input in a
array):
处理负数情况的树ONELINERS 的比较(a
数组中的输入):
var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30 chars time complexity: O(n)
var maxB = a.sort((a,b)=>b.y-a.y)[0].y; // 27 chars time complexity: O(nlogn)
var maxC = Math.max(...a.map(o=>o.y)); // 26 chars time complexity: >O(2n)
editable example here. Ideas from: maxA, maxBand maxC(side effect of maxB is that array a
is changed because sort
is in-place).
可编辑示例在这里。想法来自:maxA、maxB和maxC( maxB 的副作用是数组a
因为sort
就地而改变)。
var a = [
{"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},
{"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.024530916}
]
var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y;
var maxC = Math.max(...a.map(o=>o.y));
var maxB = a.sort((a,b)=>b.y-a.y)[0].y;
document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;
For bigger arrays the Math.max...
will throw exception: Maximum call stack size exceeded(Chrome 76.0.3809, Safari 12.1.2, date 2019-09-13)
对于更大的数组,Math.max...
将抛出异常:超出最大调用堆栈大小(Chrome 76.0.3809,Safari 12.1.2,日期 2019-09-13)
let a = Array(400*400).fill({"x": "8/11/2009", "y": 0.026572007 });
// Exception: Maximum call stack size exceeded
try {
let max1= Math.max.apply(Math, a.map(o => o.y));
} catch(e) { console.error('Math.max.apply:', e.message) }
try {
let max2= Math.max(...a.map(o=>o.y));
} catch(e) { console.error('Math.max-map:', e.message) }
回答by congusbongus
I'd like to explain the terse accepted answerstep-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:
更多信息:
回答by Guffa
Well, first you should parse the JSON string, so that you can easily access it's members:
好吧,首先您应该解析 JSON 字符串,以便您可以轻松访问它的成员:
var arr = $.parseJSON(str);
Use the map
method to extract the values:
使用该map
方法提取值:
arr = $.map(arr, function(o){ return o.y; });
Then you can use the array in the max
method:
然后你可以在max
方法中使用数组:
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; }));
回答by Vin S
var data = [
{ 'name': 'Vins', 'age': 27 },
{ 'name': 'Jan', 'age': 38 },
{ 'name': 'Alex', 'age': 80 },
{ 'name': 'Carl', 'age': 25 },
{ 'name': 'Digi', 'age': 40 }
];
var max = data.reduce(function (prev, current) {
return (prev.age > current.age) ? prev : current
});
//output = {'name': 'Alex', 'age': 80}
回答by kmonsoor
回答by Ooki Koi
Or a simple sort! Keeping it real :)
或者简单的排序!保持真实:)
array.sort((a,b)=>a.y<b.y)[0].y
回答by Diego Santa Cruz Mendezú
Each array and get max value with Math.
每个数组并使用 Math 获取最大值。
data.reduce((max, b) => Math.max(max, b.costo), data[0].costo);