Merge object & sum a single property in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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 }
]
raja
Published on 26-Aug-2020 14:58:10
Advertisements