我正在寻找一个非常快速,干净和有效的方法来获得以下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。
又快又脏:
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)));
// Here is very simple way to go:
// Your DataSet.
let numberArray = [
{
"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
}
]
// 1. First create Array, containing all the value of Y
let result = numberArray.map((y) => y)
console.log(result) // >> [0.026572007,0.025057454,0.024530916,0.031004457]
// 2.
let maxValue = Math.max.apply(null, result)
console.log(maxValue) // >> 0.031004457