首页 > 解决方案 > 计算和更新数组中的重复条目

问题描述

我有一个包含重复条目的数组。我在找:

这是我所拥有的一个例子:

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

这是一个 JsFiddle

标签: javascriptecmascript-6reduce

解决方案


您可以使用reduceobject 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);


推荐阅读