计算数组中的重复项和 return 新数组,其键值源自 Javascript 中的另一个数组

Count duplicates in an array and return new array with a key value derived from another array in Javascript

根据我之前的问题,我想更改和扩展建议的功能。

这是我得到的数据:

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
  }, {})
}

如您所知,问题在于它实际上 returns 一个新对象,而不是一个新数组。此外,我想根据 categoryId 匹配 [=19],将 categories 数组中的 categoryTitlethings 数组中的重复计数结果相结合=] 在 categories.

  // 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 }
  // ]

再次感谢。

是这样的吗?

const newArr = categories.map(category => {
    const count = things.filter(thing => thing.categoryId === category.id).length;
    return { [category.title]: count }
});
console.log(newArr);

https://jsfiddle.net/f3x6m12j/

您可以对 idtitle 的关系取 Map

const
    duplicatesCountWithTitle = (things, categories) => things.reduce((hash, { categoryId }) => {
        hash[categories.get(categoryId)] = (hash[categories.get(categoryId)] || 0) + 1
        return hash;
    }, {}),
    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 }],
    categories = [{ id: 1, title: 'Category 1' }, { id: 2, title: 'Category 2' }, { id: 4, title: 'Category 3' }],
    result = duplicatesCountWithTitle(
        things,
        categories.reduce((m, { id, title }) => m.set(id, title), new Map)
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }