Skip to content

Instantly share code, notes, and snippets.

@mizanmahi
Created June 9, 2022 08:17
Show Gist options
  • Save mizanmahi/bf9b17ead4f1b0e68659647244793d46 to your computer and use it in GitHub Desktop.
Save mizanmahi/bf9b17ead4f1b0e68659647244793d46 to your computer and use it in GitHub Desktop.
// Merging two arrays of objects
// if the object is same in both arrays, then update the quantity else add the object to the new merged array array
const arr1 = [
// from db
{ name: 'orange', qty: 5, vendor_details: { name: 'akash', vendor_id: 8 } },
{ name: 'apple', qty: 10, vendor_details: { name: 'akash', vendor_id: 8 } },
{ name: 'mango', qty: 15, vendor_details: { name: 'akash', vendor_id: 8 } },
];
const arr2 = [
// local storage
{ name: 'orange', qty: 3, vendor_details: { name: 'akash', vendor_id: 8 } },
{ name: 'apple', qty: 8, vendor_details: { name: 'akash', vendor_id: 8 } },
{ name: 'banana', qty: 12, vendor_details: { name: 'akash', vendor_id: 8 } },
];
const combined = [...arr1, ...arr2];
let tracker = [],
merged = [],
length = combined.length;
for (let i = 0; i < length; i++) {
if (tracker[combined[i].name]) {
merged.find((item) => item.name === combined[i].name).qty +=
combined[i].qty;
continue;
}
tracker[combined[i].name] = true;
merged.push(combined[i]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment