Beginner Coder
Beginner Coder

Reputation: 226

How to sum two different array if their name match

This is my two object from two different URL.I want to sum or add item distribution array if name match

0:
cancelTenders: 1
closeTenders: 7
itemDistribution: Array(4)
0: {name: "Mobile", quantity: 18472.8}
1: {name: "Laptop", quantity: 20117.535000000003}
2: {name: "Tablet", quantity: 2609.75}
3: {name: "Watch", quantity:6205}


1:
cancelTenders: 0
closeTenders: 0
itemDistribution: Array(3)
0: {name: "Mobile", quantity: 26290.65}
1: {name: "Laptop", quantity: 11844.774}
2: {name: "Tablet", quantity: 416.8}

I want to add two different array if their name match result like this

0: {name: "Mobile", quantity: 44,763.45}
1: {name: "Laptop", quantity: 31,962.309}
2: {name: "Tablet", quantity: 3,026.55}
3: {name: "Watch", quantity: 6205}

Upvotes: 0

Views: 525

Answers (1)

zb22
zb22

Reputation: 3231

You can first merge both arrays,
Then use Array.prototype.reduce() to make an object for each key and finally use Object.values to achieve the output you want.

const arr1 = [
  {name: "Mobile", quantity: 18472.8},
  {name: "Laptop", quantity: 20117.535000000003},
  {name: "Tablet", quantity: 2609.75},
  {name: "Watch", quantity:6205}
]

const arr2 = [
  {name: "Mobile", quantity: 26290.65},
  {name: "Laptop", quantity: 11844.774},
  {name: "Tablet", quantity: 416.8}
]

const res = Object.values([...arr1, ...arr2].reduce((acc, curr) => {
   if(!acc[curr.name]) {
     acc[curr.name] = curr;
   } else {
     acc[curr.name].quantity += curr.quantity;
   }
    
   return acc;
   
}, {}));

console.log(res)

references:

Array.prototype.reduce()
Object.values()
merge arrays with spread operator

Upvotes: 4

Related Questions