请教大家个问题,对象数组去除重复数据,并且累加数量?

let arr = [
  {
    code: "10AT",
    batch: "1027",
    store: "001",
    number: 10,
  },
  {
    code: "10AT",
    batch: "1027",
    store: "001",
    number: 10,
  },
  {
    code: "10AT",
    batch: "1027",
    store: "002",
    number: 10,
  },
  {
    code: "10AAT",
    batch: "1027",
    store: "002",
    number: 100,
  },
];

需要将code,batch,store都相同的number累加,并且去除重复项,结果为

let result = [
  {
    code: "10AT",
    batch: "1027",
    store: "001",
    number: 20,
  },
  {
    code: "10AT",
    batch: "1027",
    store: "002",
    number: 10,
  },
  {
    code: "10AAT",
    batch: "1027",
    store: "002",
    number: 100,
  },
];
阅读 1.3k
2 个回答

基本思路:分组→按组合计→处理成结果视图

用 Lodash

const result = _(arr).groupBy(({ code, batch, store }) => [code, batch, store].join("|"))
    .values()
    .map(list => {
        const { code, batch, store } = list[0];
        return { code, batch, store, number: _.sumBy(list, "number") };
    })
    .value();

自己写

const result = Object.values(
    arr.reduce((r, { code, batch, store, number }) => {
        const key = `${code}|${batch}|${store}`;
        const item = r[key] ??= { code, batch, store, number: 0 };
        item.number += number;
        return r;
    }, {})
);
let hash = {};

// 利用 hash 存相同值和计算
for(let i = 0; i < arr.length; i++) {
  let key = [arr[i].code, arr[i].batch, arr[i].store].join("-");
  hash[key] = (hash[key] || 0) + arr[i].number;
}

// 重新组装数据
const result = Object.entries(hash).map(([keys, value]) => {
  const [code, batch, store] = keys.split("-");
  return {code, batch, store, number: value}
})

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏