Reputation: 15
I have this kind of data
How do I filter it and count it. The result that I'm trying to get is as follows:
Oct : 2 Nov : 3
This is the code that i have been trying
let data = new Set(this.products.map(item => item.date))
data.forEach((date)=>{
this.resultData.push({
date: date,
products: this.products.filter(i => i.date === date)
})
})
should i just change to normal js for loop or using ts foreach loop?
Upvotes: 1
Views: 74
Reputation: 15083
I think you can remove one of the loops when running forEach
then later filtering, see below example
const dates = [
"2020-02-29T08:00:00.000Z",
"2019-12-31T08:00:00.000Z",
"2020-10-01T08:00:00.000Z",
"2020-03-31T08:00:00.000Z",
"2020-10-01T08:00:00.000Z",
"2020-10-01T08:00:00.000Z",
"2020-05-31T08:00:00.000Z",
"2020-02-29T08:00:00.000Z",
"2020-08-31T08:00:00.000Z",
"2020-06-30T08:00:00.000Z",
"2019-12-31T08:00:00.000Z",
"2020-02-29T08:00:00.000Z",
"2020-02-29T08:00:00.000Z",
"2020-08-31T08:00:00.000Z"
];
const summary = dates.reduce((p, n) => {
const d = new Date(n).toLocaleDateString(undefined, {
month: 'short'
})
return ({ ...p, [d]: typeof p[d] !== 'undefined' ? p[d] + 1 : 1 })
}, {})
console.log(summary)
Upvotes: 1