我正在寻找一种非常快速、干净和有效的方法来获得以下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
。
发布于 2010-10-26 05:04:59
在array
中查找对象的最大y
值
Math.max.apply(Math, array.map(function(o) { return o.y; }))
发布于 2015-12-04 11:55:03
在对象数组中查找其属性"Y“具有最大值的对象
一种方法是使用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://caniuse.com/#search=reduce (IE9及以上版本)
如果你不需要支持IE (只有Edge),或者可以使用像Babel这样的预编译器,你可以使用更简洁的语法。
const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
发布于 2016-09-13 03:43:53
干净而简单的ES6 (巴别塔)
const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);
如果arrayToSearchIn
为空,则第二个参数应确保为默认值。
https://stackoverflow.com/questions/4020796
复制