Ser*_*rov 3 javascript arrays lodash
我试图获取对象数组中的数组值的最大值和最小值,如下所示:
[
{
id: 1,
enabled: false,
layer: 'Mood',
color: '#f16c63',
points: [
{date: '2013-01-02', value: 20},
{date: '2013-02-02', value: 15},
{date: '2013-03-12', value: 24},
{date: '2013-03-23', value: 18},
{date: '2013-03-24', value: 22},
{date: '2013-04-09', value: 12},
{date: '2013-06-13', value: 16},
{date: '2013-06-14', value: 20},
]
},
{
id: 2,
enabled: true,
layer: 'Performance',
color: '#698bfc',
points: [
{date: '2013-01-02', value: 15},
{date: '2013-02-02', value: 24},
{date: '2013-03-12', value: 29},
{date: '2013-03-23', value: 21},
{date: '2013-03-24', value: 20},
{date: '2013-04-09', value: 17},
{date: '2013-06-13', value: 25},
{date: '2013-06-14', value: 21},
]
},
{
id: 3,
enabled: false,
layer: 'Fatigue',
color: '#e1fc6a',
points: [
{date: '2013-01-02', value: 32},
{date: '2013-02-02', value: 27},
{date: '2013-03-12', value: 30},
{date: '2013-03-23', value: 31},
{date: '2013-03-24', value: 27},
{date: '2013-04-09', value: 15},
{date: '2013-06-13', value: 20},
{date: '2013-06-14', value: 18},
]
},
{
id: 4,
enabled: true,
layer: 'Hunger',
color: '#63adf1',
points: [
{date: '2013-01-02', value: 12},
{date: '2013-02-02', value: 15},
{date: '2013-03-12', value: 13},
{date: '2013-03-23', value: 17},
{date: '2013-03-24', value: 10},
{date: '2013-04-09', value: 14},
{date: '2013-06-13', value: 12},
{date: '2013-06-14', value: 11},
]
},
]
Run Code Online (Sandbox Code Playgroud)
我需要从points数组中获取最大值和最小值.似乎我可以做这样的事情,最大值和类似的最小值:
var maxDate = _.max(dataset, function (area) {
return _.max(area.points, function (point) {
console.log(new Date(point.date).getTime())
return new Date(point.date).getTime()
})
});
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,这会让我 - 无限.使用嵌套的_.max()运行是否合法?我使用这种方法与D3.js库工作得很好.
请指教.
内部_.max将返回具有最大日期的点,但是您传递给外部的函数_.max需要一个可以比较的值.比较这些值时,它将返回具有最大值的图层.
听起来你想要从所有可用层中获得最大点(这是正确的)吗?
如果是这样,你可以这样做:
function pointDate(point) {
console.log(new Date(point.date).getTime())
return new Date(point.date).getTime()
}
var maxDate = _.max(_.map(dataset, function (area) {
return _.max(area.points, pointDate);
}), pointDate);
Run Code Online (Sandbox Code Playgroud)
这将返回所有点的最大日期的点对象.
这是一个很好的功能风格的方法:
function pointDate(point) {
console.log(new Date(point.date).getTime())
return new Date(point.date).getTime()
}
var maxDate = _(dataset).map('points').flatten().max(pointDate);
Run Code Online (Sandbox Code Playgroud)