- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ]
Advertisements