javascript - 计算和更新数组中的重复条目
问题描述
我有一个包含重复条目的数组。我在找:
- 删除所有重复的事件
- 如果我们发现一个元素,则增加一个元素的 val 属性
这是我所拥有的一个例子:
const arr = [
{"id":"46","name":"Productivity","val":1},
{"id":"1","name":"test","val":1},
{"id":"43","name":"Health and Fitness","val":1},
{"id":"46","name":"Productivity","val":1},
{"id":"1","name":"test","val":1},
{"id":"46","name":"Productivity","val":1}
]
// 想要的结果
const result = [
{"id":"46","name":"Productivity","val":3},
{"id":"43","name":"Health and Fitness","val":1},
{"id":"1","name":"test","val":2}
]
解决方案
您可以使用reduce和object destructuring轻松实现此目的。
const arr = [
{ id: "46", name: "Productivity", val: 1 },
{ id: "1", name: "test", val: 1 },
{ id: "43", name: "Health and Fitness", val: 1 },
{ id: "46", name: "Productivity", val: 1 },
{ id: "1", name: "test", val: 1 },
{ id: "46", name: "Productivity", val: 1 },
];
const result = arr.reduce((acc, curr) => {
const { id, name, val } = curr;
const isPresent = acc.find((el) => el.id === id);
if (!isPresent) acc = [...acc, { id, name, val }];
else isPresent.val = isPresent.val + val;
return acc;
}, []);
console.log(result);
推荐阅读
- javascript - 如果频道不是 NSFW,如何从帮助菜单中隐藏 NSFW 命令
- javascript - 为什么join()不会从javascript中的数组中删除空字符串?
- excel - 同步两个不同的工作簿
- ios - 动态改变 iOS LaunchScreen
- csv - 解析文件时如何忽略分隔符定义?
- fastapi - FastAPI Async Def 调用常用函数
- google-sheets - Google 表格中的迷你图显示选项错误
- javascript - npm i ts-node-dev --save-dev 导致没有这样的文件或目录,chmod node_modules/ts-node-dev/lib\bin.js'
- python - 如何阻止 Telegram 机器人执行旧代码
- linux - 获取正在运行的 linux 发行版的名称