freeCodeCamp/Algorithms/inventoryUpdate.js

41 lines
917 B
JavaScript
Raw Permalink Normal View History

2023-08-22 02:50:06 +02:00
// 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"],
]
)
);