【发布时间】:2015-03-04 13:17:54
【问题描述】:
我试图在对象数组中获取数组值的最大值和最小值,如下所示:
[
{
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},
]
},
]
我需要从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()
})
});
但由于某种原因,这让我返回 -Infinity。使用嵌套的 _.max() 运行是否合法?我将这种方法与 D3.js 库一起使用,效果很好。
请指教。
【问题讨论】:
-
来自doc:如果集合为空或错误,则返回无穷大。
-
_.maxreturn object with max field value = not max field value,所以当你从嵌套的_.max返回时它返回对象而不是字段值
标签: javascript arrays lodash