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

标签 javascript arrays count duplicates

我有以下 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/

相关文章:

javascript - 一个字符串中的两种颜色和一种功能?

WPF DataBinding 在绑定(bind)中指定数组索引不起作用

java - 如何删除三重线

php - PDO 选择倍数 count()

mysql - 使用多个 SELECT 优化 SQL 查询

bash - grep 数字范围

javascript - 从输入下拉列表中获取所选值的索引/区分重复值

javascript - jQuery 循环添加幻灯片 "alt"

javascript - 如何在javascript中#include?

javascript - 功能:根据字符串中是否存在子字符串返回 True/False