javascript - 查找对象数组中属性的最大值
我正在寻找一种非常快速,干净和有效的方法来获取以下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循环是唯一可行的方法吗? 我非常热衷于使用Math.max。
Rio asked 2019-02-26T22:09:11Z
11个解决方案
464 votes
要在array中找到对象的最大值y:
Math.max.apply(Math, array.map(function(o) { return o.y; }))
tobyodavies answered 2019-02-26T22:09:21Z
129 votes
在对象数组中查找属性“X”具有最大值的对象
一种方法是使用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/Reduce][http: