我有以下 array
,我想返回一个新数组,其中包含重复 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'
}
]
我设法组合了一个简单的函数,它返回重复 id
的计数(见下文),但它也返回 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
值(例如4
关于类别 3)。
我错过了什么?
非常感谢。
最佳答案
您可以直接获取 categoryTitle
,而无需事先映射数组。
function categoriesCount (things) {
return things.reduce((hash, { categoryTitle }) => {
hash[categoryTitle] = (hash[categoryTitle] || 0) + 1;
return hash;
}, {});
}
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' }]
console.log(categoriesCount(things));
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 使用 Javascript 计算数组中的重复值并返回带有附加值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59193725/