首页 > 解决方案 > 从数组中删除重复的对象但也会增加数量

问题描述

我有这个清单:

const list = [
  { name: 'AA', quantity: 1 },
  { name: 'AA', quantity: 1 },
  { name: 'BB', quantity: 1 },
  { name: 'CC', quantity: 1 },
  { name: 'CC', quantity: 2 },
]

我正在寻找的输出应该如下所示:

const newlist = [
  { name: 'AA', quantity: 2 },
  { name: 'BB', quantity: 1 },
  { name: 'CC', quantity: 3 },
]

此代码删除重复项,但我无法弄清楚当存在重复项时如何增加数量。

const setObj = new Set()
const result = list.reduce((acc, item) => {
  if (!setObj.has(item.name)) {
    setObj.add(item.name)
    acc.push({ name: item.name, quantity: item.quantity })
  }

  // for (const iterator of list) {
  //   if (setObj.has(item.name)) {
  //     console.log(' ~ file: Untitled-1 ~ line 15 ~ iterator', iterator)
  //   }
  // }

  console.log()
  return acc
}, [])

标签: javascriptarraysobject

解决方案


您可以reduce在结果数组中使用 then find 元素,如果它不存在push它到,array否则在 result 中找到它的add当前元素。quantityelementarray

代码:

const list=[{name:"AA",quantity:1},{name:"AA",quantity:1},{name:"BB",quantity:1},{name:"CC",quantity:1},{name:"CC",quantity:2}];

const res = list.reduce((acc, e) => {
  const found = acc.find(x => e.name === x.name)
  found ? found.quantity += e.quantity : acc.push(e)
  return acc
}, [])

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


推荐阅读