我有Array<object>,它包含类型为n的对象
{
name: 'random',
startDate: '2017-11-10 09:00',
endDate: '2017-11-23 11:00'
}我想要的是,在呈现结果之前,在新 Array<object中过滤这个数组,它包含startDate (以及它的唯一,2017-11-10 09:00和2017-11-10 10:00并不是统一的)和一个counter,这个Date在数据数组中的次数是多少次。我怎样才能做到这一点?
发布于 2017-11-07 12:01:34
您可以首先像这样使用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);.as-console-wrapper { max-height: 100% !important; top: 0; }
发布于 2017-11-07 13:42:15
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);.as-console-wrapper { max-height: 100%!important; top: 0; }
https://stackoverflow.com/questions/47157390
复制相似问题