【问题标题】:Remove only parts of duplicates in array of objects仅删除对象数组中的部分重复项
【发布时间】:2023-01-17 18:33:43
【问题描述】:

这真让我抓狂。我有一组要减少的对象。

我的状态 objArr 中有这一系列产品:

]
0: {item: 'Item 1', value: 1}
1: {item: 'Item 2' value: 3}
2: {item: 'Item 3', value: 5}
3: {item: 'Item 1', value: 3}
4: {item: 'Item 2', value: 5}
]

但我希望它是:

[
0: {item: 'Item 1', value: 4}
1: {item: 'Item 2' value: 8}
2: {item: 'Item 3', value: 5}
]

我只设法删除了整个对象,而不仅仅是键值对。有人能帮我吗?

这是我能得到的最接近的......

const findDuplicates = () => {

    return objArr?.reduce((arr, item) => {
        const removed = arr?.filter(i => i.item !== item.item)
        const dup = [...removed, item]
        
        return dup
    
    }, [])

}

输出

[
0: {item: 'Item 3', value: 5}
1: {item: 'Item 1', value: 3}
2: {item: 'Item 2', value: 5}
]

【问题讨论】:

    标签: reactjs arrays object duplicates reduce


    【解决方案1】:

    正如您提到的,使用 reducevalue 属性来总结它们:

    const groupByItem = objArr.reduce((acc, curr) => {
      if (acc[curr.item]) {
        acc[curr.item].value += curr.value;
      } else {
        acc[curr.item] = { item: curr.item, value: curr.value };
      }
      return acc;
    }, {});
    
    const groupedArray = Object.values(groupByItem);
    

    【讨论】:

      猜你喜欢
      • 2012-11-24
      • 2017-09-01
      • 1970-01-01
      • 2020-02-26
      • 2017-04-10
      • 2016-03-12
      相关资源
      最近更新 更多