del*_*ing -3 javascript arrays typescript
我想获得最高的数组值(只有'y'),我该怎么做?
我只将数组设置的值转换为[]
类似的值[0]
data = [
{
values: [
{ x:'2017-01', y: 1.2 },
{ x:'2017-02', y: 1.3 },
{ x:'2017-03', y: 1.5 },
{ x:'2017-04', y: 1.6 },
{ x:'2017-05', y: 1.8 },
{ x:'2017-06', y: 1.9 },
{ x:'2017-07', y: 1.5 },
{ x:'2017-08', y: 1.7 },
{ x:'2017-09', y: 1.5 },
{ x:'2017-10', y: 0 }
]
}
];
data.forEach(function(d) {
console.log(Math.max(d.values[0].y));
});
Run Code Online (Sandbox Code Playgroud)
我假设你想获得最大价值的对象y
从data[0].values
,因为data
它本身是一个只有一个元素的数组.
如果只想获得y
(1.9)的最大值,可以使用Math.max,但是如果要获得具有最大值的整个对象,则y
需要再次遍历数组以查找具有的对象y == 1.9
.
相反,您可以使用Array.prototype.reduce同时执行这两个操作,它遍历调用每个元素上的回调的数组,类似于Array.prototype.forEach,除了您在每次迭代时从回调返回的值作为参数传递给下一次迭代
data = [
{
values: [
{ x:'2017-01', y: 1.2 },
{ x:'2017-02', y: 1.3 },
{ x:'2017-03', y: 1.5 },
{ x:'2017-04', y: 1.6 },
{ x:'2017-05', y: 1.8 },
{ x:'2017-06', y: 1.9 },
{ x:'2017-07', y: 1.5 },
{ x:'2017-08', y: 1.7 },
{ x:'2017-09', y: 1.5 },
{ x:'2017-10', y: 0 }
]
}
];
var max = data[0].values.reduce( function( maxSoFar, current ) {
// If current.y is larger than maxSoFar.y, return current
// so that it becomes maxSoFar for the next iteration
return current.y > maxSoFar.y ? current : maxSoFar;
});
console.log( max );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
80 次 |
最近记录: |