comparing and adding items to array of objects

前端 未结 4 2004
闹比i
闹比i 2021-01-25 04:13

The below code is supposed to:

1) go through the two arrays,

2) if an item exist in both arrays, add its value to the value of the similar item in the first arra

4条回答
  •  离开以前
    2021-01-25 04:35

    You could use a hash table for the inventory and check against and update currInv.

    var curInv = [[21, "Bowling Ball"], [2, "Dirty Sock"], [2, "cat"], ],
        newInv = [[21, "Bowling Ball"], [2, "Dirty Sock"], [3, "rags"], [3, "mugs"]],
        inventory = Object.create(null);
    
    curInv.forEach(function (a) {
        this[a[1]] = a;
    }, inventory);
    
    newInv.forEach(function (a) {
        if (!this[a[1]]) {
            this[a[1]] = [0, a[1]];
            curInv.push(this[a[1]]);
        }
        this[a[1]][0] += a[0];
    }, inventory);
    
    console.log(curInv);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题