Reputation: 43
I have a list of dates like this:
[ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ]
how to return a count of the items in list which is this same?
for example:
{date: "2020-08-20", count: 2},
{date: "2020-08-21", count: 1},
{date: "2020-08-24", count: 1},
{date: "2020-08-25", count: 3},
thanks for any help
Upvotes: 2
Views: 100
Reputation: 31
I think you could something like:
const yourArray = [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ]
const result = yourArray
.filter((item, pos) => yourArray.indexOf(item) == pos)
.map(item => ({
date: item,
count: yourArray.filter(current => current === item).length
}))
console.log(result)
Upvotes: 3
Reputation: 3302
You can use array reduce method to count it. Traverse the string array and count the frequencies. At last print the result using Object.values method.
const data = [
'2020-08-20',
'2020-08-20',
'2020-08-21',
'2020-08-24',
'2020-08-25',
'2020-08-25',
'2020-08-25',
];
const ret = data.reduce((prev, c) => {
const p = prev;
if (!p[c]) p[c] = { date: c, count: 1 };
else p[c] = { date: c, count: p[c].count + 1 };
return p;
}, {});
console.log(Object.values(ret));
Upvotes: 4
Reputation: 8751
const ary = [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ]
const result = []
ary.forEach(d => {
const index = result.findIndex(r => r.date === d)
if (index === -1) {
result.push({
date: d,
count: 1
})
} else {
result[index].count ++;
}
})
console.log(result)
Upvotes: 6