I've got the following array and I'd like to return a new array containing the count of the duplicate ids along with the value of the id:
const things = [
{
id: 1,
title: 'Something',
categoryId: 1,
categoryTitle: 'Category 1'
},
{
id: 2,
title: 'Another thing',
categoryId: 1,
categoryTitle: 'Category 1'
},
{
id: 3,
title: 'Yet another thing',
categoryId: 2,
categoryTitle: 'Category 2'
},
{
id: 4,
title: 'One more thing',
categoryId: 4,
categoryTitle: 'Category 3'
},
{
id: 5,
title: 'Last thing',
categoryId: 4,
categoryTitle: 'Category 3'
}
]
I've managed to put together a simple function that returns the count of duplicate ids (see below), but it also return the id (i.e. 1, 2, 4):
function categoriesCount (things) {
const thingsMapped = things.map(thing => thing.categoryId)
return thingsMapped.reduce((map, val) => {
map[val] = (map[val] || 0) + 1
return map
}, {})
}
console.log('categoriesCount', categoriesCount(things))
Returns:
"categoriesCount" Object {
1: 2,
2: 1,
4: 2
}
Whereas I'd like it to return:
"categoriesCount" Object {
'Category 1': 2,
'Category 2': 1,
'Category 3': 2
}
Note: the category title's numeric value (e.g. Category 3) may not match it's id value (e.g. 4 with regards to Category 3).
What am I missing?
Many thanks in advance.
map[val]withmap['Categories ' + val]???