【发布时间】:2020-03-30 07:13:25
【问题描述】:
我有以下array,我想返回一个新数组,其中包含重复的ids 的计数以及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'
}
]
我已经设法组合了一个简单的函数,它返回重复 ids 的计数(见下文),但它也返回 id(即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))
返回:
"categoriesCount" Object {
1: 2,
2: 1,
4: 2
}
而我希望它返回:
"categoriesCount" Object {
'Category 1': 2,
'Category 2': 1,
'Category 3': 2
}
注意:类别标题的数值(例如类别 3)可能与它的 id 值不匹配(例如,关于类别 3 的 4)。
我错过了什么?
非常感谢。
【问题讨论】:
-
最后 2 个对象的标题不应该是“Category 4”以获得该输出吗?
-
键是类别标签还是后跟 categoryId 的通用“类别”标签?
-
将
map[val]的所有实例替换为map['Categories ' + val]???
标签: javascript arrays count duplicates