javascript - 从数组中删除重复的对象但也会增加数量
问题描述
我有这个清单:
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
}, [])
解决方案
您可以reduce
在结果数组中使用 then find 元素,如果它不存在push
它到,array
否则在 result 中找到它的add
当前元素。quantity
element
array
代码:
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; }
推荐阅读
- rabbitmq - RabbitMQ、Vernemq 和 HiveMQ - 分发和 HA
- html - 设置表单中元素的宽度(以及在 DIV 中)
- c++ - 带有模板的类的构造函数
- spring-boot - 错误 SpringApplication IllegalAccessError 试图访问方法 org.springframework.beans.PropertyEditorRegistrySupport.getDefaultEditor
- python - TypeError:“响应”类型的对象没有 len()
- c++ - C++/Rcpp::NumericVector 的奇怪行为:在 C++ 中更新向量的值会导致 R 中不同向量的更新
- mysql - 如何在mysql中按日期对这个字段求和
- react-native - Reducer 在初始化期间返回 undefined
- python - 使用 import youtube_dl 在 python 脚本中使用 Youtube-dl
- mysql - 删除数据库中除最后日期外的所有项目