Skip to content

Instantly share code, notes, and snippets.

@alexcastrodev
Created November 6, 2024 02:04
Show Gist options
  • Save alexcastrodev/30ea3a5b107ca1296e7a4a6bddb34192 to your computer and use it in GitHub Desktop.
Save alexcastrodev/30ea3a5b107ca1296e7a4a6bddb34192 to your computer and use it in GitHub Desktop.
const online_basket = [
{ id: 1, quantity: 2 },
{ id: 3, quantity: 1 },
]
const offline_basket = [
{ id: 5, quantity: 1 },
{ id: 3, quantity: 2 },
{ id: 1, quantity: 1 }
]
function mergeBaskets(online, offline) {
const mergedBasket = [...online];
offline.forEach(offlineItem => {
const existingItem = mergedBasket.find(item => item.id === offlineItem.id);
if (existingItem) {
if (offlineItem.quantity > existingItem.quantity) {
existingItem.quantity = offlineItem.quantity;
}
} else {
mergedBasket.push(offlineItem);
}
});
return mergedBasket;
}
mergeBaskets(online_basket, offline_basket)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment