我正在寻找一个非常快速,干净和有效的方法来获得以下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。
非常简单
const array1 = [
{id: 1, val: 60},
{id: 2, val: 2},
{id: 3, val: 89},
{id: 4, val: 78}
];
const array2 = [1,6,8,79,45,21,65,85,32,654];
const max = array1.reduce((acc, item) => acc = acc > item.val ? acc : item.val, 0);
const max2 = array2.reduce((acc, item) => acc = acc > item ? acc : item, 0);
console.log(max);
console.log(max2);
又快又脏:
Object.defineProperty (Array.prototype“分钟”,
{
价值:函数(f)
{
F = F || (v => v);
返回。Reduce ((a, b) => (f(a) < f(b)) ?A: b);
}
});
Object.defineProperty (Array.prototype‘麦克斯’,
{
价值:函数(f)
{
F = F || (v => v);
返回。Reduce ((a, b) => (f(a) > f(b)) ?A: b);
}
});
console.log ([1, 2, 3] .max ());
console.log([1, 2, 3]。Max (x => x*(4-x)));
console.log ([1, 2, 3] .min ());
console.log([1, 2, 3]。Min (x => x*(4-x)));