【发布时间】:2020-03-30 13:16:27
【问题描述】:
继我之前的问题之后,我想更改和扩展建议的功能。
这是我得到的数据:
const things = [
{
id: 1,
title: 'Something',
categoryId: 1
},
{
id: 2,
title: 'Another thing',
categoryId: 1
},
{
id: 3,
title: 'Yet another thing',
categoryId: 2
},
{
id: 4,
title: 'One more thing',
categoryId: 4
},
{
id: 5,
title: 'Last thing',
categoryId: 4
}
]
const categories = [
{
id: 1,
title: 'Category 1'
},
{
id: 2,
title: 'Category 2'
},
{
id: 4,
title: 'Category 3'
}
]
之前我已经被展示了如何按照这些思路做某事:
const duplicatesCountWithTitle = (things, categories) => {
const thingsReduced = things.reduce((hash, { categoryId }) => {
hash[categoryId] = (hash[categoryId] || 0) + 1
return hash
}, {})
}
如您所知,问题在于它实际上返回了一个新对象,而不是一个新数组。此外,我想将categories 数组中的categoryTitle 与things 数组中的重复计数结果结合起来,基于categoryId 匹配categories 中的id。
// currently the above returns an object in the structure of:
// {
// 1: 2,
// 2: 1,
// 4: 2
// }
// what I'm after is an array like this:
// [
// { 'Category 1': 2 },
// { 'Category 2': 1 },
// { 'Category 3': 2 }
// ]
再次感谢您。
【问题讨论】:
-
所需的结果是否只是每个类别的计数器?
-
@Trace - 期望的结果是:
[ { 'Category 1': 2 }, { 'Category 2': 1 }, { 'Category 3': 2 } ]其中值是匹配每个类别的事物的计数。
标签: javascript arrays duplicates derived