diff --git a/Algorithms/inventoryUpdate.js b/Algorithms/inventoryUpdate.js new file mode 100644 index 0000000..8dd4d24 --- /dev/null +++ b/Algorithms/inventoryUpdate.js @@ -0,0 +1,40 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/inventory-update + +function updateInventory(arr1, arr2) { + const inventory = {}; + arr1.forEach(([quantity, item]) => { + inventory[item] = quantity; + }); + arr2.forEach(([quantity, item]) => { + if (inventory[item]) { + inventory[item] += quantity; + } else { + inventory[item] = quantity; + } + }); + const inventoryArr = []; + for (const [item, quantity] of Object.entries(inventory)) { + inventoryArr.push([quantity, item]); + } + inventoryArr.sort(([quantityA, itemA], [quantityB, itemB]) => + itemA > itemB ? 1 : -1 + ); + return inventoryArr; +} + +console.log( + updateInventory( + [ + [21, "Bowling Ball"], + [2, "Dirty Sock"], + [1, "Hair Pin"], + [5, "Microphone"], + ], + [ + [2, "Hair Pin"], + [3, "Half-Eaten Apple"], + [67, "Bowling Ball"], + [7, "Toothpaste"], + ] + ) +);