From ecad95a4e8875fa64164b5b4862212f0aba18bf8 Mon Sep 17 00:00:00 2001 From: Manish Date: Tue, 22 Aug 2023 10:50:06 +1000 Subject: [PATCH] Algorithms: Inventory Update --- Algorithms/inventoryUpdate.js | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Algorithms/inventoryUpdate.js 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"], + ] + ) +);