且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较项目并将其添加到对象数组

更新时间:2023-12-02 23:23:04

您可以使用哈希表作为清单,并检查并更新currInv.

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