Merge object & sum a single property in JavaScript


Let’s say, we have two arrays of objects that contain information about some products of a company −

const first = [
   {
      id: "57e7a1cd6a3f3669dc03db58",
      quantity:3
   },
   {
      id: "57e77b06e0566d496b51fed5",
      quantity:3
   },
   {
      id: "57e7a1cd6a3f3669dc03db58",
      quantity:3
   },
   {
      id: "57e77b06e0566d496b51fed5",
      quantity:3
   }
];
const second = [
   {
      id: "57e7a1cd6a3f3669dc03db58",
      quantity:6
   },
   {
      id: "57e77b06e0566d496b51fed5",
      quantity:6
   }
];

We are now required to write a function that merges the two arrays, such that the objects with same ids do not make repetitive appearances and moreover, the quantity property for objects duplicate id gets added together.

Therefore, let’s write the code for this function −

Example

const first = [
   {
      id: "57e7a1cd6a3f3669dc03db58",
      quantity:3
   },
   {
      id: "57e77b06e0566d496b51fed5",
      quantity:3
   },
   {
      id: "57e7a1cd6a3f3669dc03db58",
      quantity:3
   },
   {
      id: "57e77b06e0566d496b51fed5",
      quantity:3
   }
];
const second = [
   {
      id: "57e7a1cd6a3f3669dc03db58",
      quantity:6
   },
   {
      id: "57e77b06e0566d496b51fed5",
      quantity:6
   }
];
const mergeArray = (first, second) => {
   return [...first, ...second].reduce((acc, val, i, arr) => {
      const { id, quantity } = val;
      const ind = acc.findIndex(el => el.id === id);
      if(ind !== -1){
         acc[ind].quantity += quantity;
      }else{
         acc.push({
            id,
            quantity
         });
      }
      return acc;
   }, []);
}
console.log(mergeArray(first, second));

Output

The output in the console will be −

[
   { id: '57e7a1cd6a3f3669dc03db58', quantity: 12 },
   { id: '57e77b06e0566d496b51fed5', quantity: 12 }
]

Updated on: 26-Aug-2020

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements