首页 > 解决方案 > 更新已经存在的数组并将新数据推送到同一个数组中

问题描述

我想将数组值推送到另一个数组中,但如果已经存在数据可用,那么在推送数据时它应该只更新现有数据。代码在打字稿中。


class itemList{
    constructor(public name: string, public amount: number){}
}

function DisArr(Ar1: itemList[]){
    for(let item of Ar1){
        console.log(item.name + " -- " + item.amount);
    }
}

var Ar1 = [new itemList('Apple',3),
new itemList('Tomato',4),
new itemList('Jam',1)];

var Ar2 = [new itemList('Orange',3),
new itemList('Tomato',8),
new itemList('Grape',20)];

console.log("Array before updating : ");
DisArr(Ar1);
Ar1.push(...Ar2);
console.log("Array before updating : ");
DisArr(Ar1);

截至目前,输出为: *Array before updates : Apple -- 3 Tomato -- 4 Jam -- 1

更新后的数组:Apple -- 3 Tomato -- 4 Jam -- 1 Orange -- 3 Tomato -- 8 Grape -- 20*

但我希望输出为:*更新前的数组:Apple -- 3 Tomato -- 4 Jam -- 1

更新后的数组:Apple -- 3 Tomato -- 12 Jam -- 1 Orange -- 3 Grape -- 20*

如何更改代码以获得所需的输出?

标签: typescript

解决方案


我有另一种解决方案使用reduce方法并删除 Ar2 中的重复项,concat如下所示

let result = Ar1.reduce((acc, item) => {
      let found = Ar2.find(c => c.name == item.name);
      if (found != undefined) {
        item.amount += found.amount;
        const index = Ar2.indexOf(found);
        if (index > -1) {
          Ar2.splice(index, 1);
        }
      }
      acc.push(item);
      return acc;
    }, []);

    result = result.concat(Ar2);

在 stackbliz 演示https://stackblitz.com/edit/angular-merge-array-reduce


推荐阅读