我有Array<object>
,其中包含<{p>类型的n
个对象
{
name: 'random',
startDate: '2017-11-10 09:00',
endDate: '2017-11-23 11:00'
}
我想要的是,在渲染结果之前,在新 Array<object
中过滤此数组,其中包含startDate
(及其唯一的2017-11-10 09:00
和{ {1}}不是uniques)和2017-11-10 10:00
这个counter
在数据数组中的次数。我怎样才能做到这一点?
答案 0 :(得分:1)
您可以先使用Array.prototype.reduce()这样:
const dates = [{
name: 'random',
startDate: '2017-11-10 09:00',
endDate: '2017-11-23 11:00'
},
{
name: 'random',
startDate: '2017-11-10 09:00',
endDate: '2017-11-23 11:00'
},
{
name: 'random',
startDate: '2017-11-10 09:00',
endDate: '2017-11-23 11:00'
},
{
name: 'random',
startDate: '2017-08-12 09:00',
endDate: '2017-11-23 11:00'
}
];
const hash = dates.reduce((a, c) => (a[c.startDate] = ++a[c.startDate] || 1, a), {});
const uniqueDates = Object.keys(hash).map(k => ({ startDate: k, counter: hash[k] }));
console.log(uniqueDates);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 1 :(得分:1)
var dateList = [{
name: 'foo',
startDate: '2017-11-10 09:00',
endDate: '2017-11-23 11:00'
}, {
name: 'bar',
startDate: '2017-11-10 09:01',
endDate: '2017-11-23 11:00'
}, {
name: 'baz',
startDate: '2017-11-10 09:00',
endDate: '2017-11-24 10:00'
}, {
name: 'biz',
startDate: '2017-11-10 09:01',
endDate: '2017-11-25 09:00'
}, {
name: 'quick',
startDate: '2017-11-10 09:00',
endDate: '2017-11-23 11:00'
}, {
name: 'brown',
startDate: '2017-12-10 09:00',
endDate: '2017-11-23 11:00'
}, {
name: 'fox',
startDate: '2017-12-10 10:00',
endDate: '2017-11-23 11:00'
}];
var startDateCountList = dateList.reduce(function (collector, dateItem) {
var
startDate = dateItem.startDate,
dateCount = collector.registry[startDate];
if (!dateCount) {
dateCount = collector.registry[startDate] = {
startDate : dateItem.startDate,
count : 0
};
collector.list.push(dateCount);
}
dateCount.count += 1;
return collector;
}, {
registry: {},
list: []
}).list;
console.log('startDateCountList : ', startDateCountList);
&#13;
.as-console-wrapper { max-height: 100%!important; top: 0; }
&#13;