Interview _algorithm_02:Inventory Update

function updateInventory(arr1, arr2) {

outer:

for (let el2 of arr2) {

    for (let el1 of arr1) {

        if (el1[1] == el2[1]) {

            el1[0] += el2[0];

            continue outer;

        }

    }

    arr1.push(el2)

}

arr1.sort(function compare(a, b) {

    if (a[1][0] < b[1][0]) {           // 按某种排序标准进行比较, a 小于 b

        return -1;

    }

    if (a[1][0] > b[1][0]) {

        return 1;

    }

    // a must be equal to b

    return 0;

})

return arr1;

}

// Example inventory lists

var curInv = [

[21, "Bowling Ball"],

[2, "Dirty Sock"],

[1, "Hair Pin"],

[5, "Microphone"]

];

var newInv = [

[2, "Hair Pin"],

[3, "Half-Eaten Apple"],

[67, "Bowling Ball"],

[7, "Toothpaste"]

];

updateInventory(curInv, newInv);

1 个赞