计算数组中的重复值,并使用Javascript返回带有附加值的计数

尼尔·默顿

我有以下内容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
}

注意:类别标题的数字值(例如Category 3)可能与它的id不匹配(例如4,关于Category 3)。

我想念什么?

提前谢谢了。

妮娜·斯科茨(Nina Scholz)

您可以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; }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章