- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
What is the best way to reduce and merge a collection of objects – JavaScript?
The best way to reduce and merge a collection of objects, use the concept of Object.values() along with reduce().
Following is the object −
var details = [ { studentId: 10, marks: 75, studentName: "John" }, { studentId: 10, marks: 75, studentName: "John" }, { studentId: 11, marks: 98, studentName: "Bob" } ];
Example
Following is the code to reduce and merge −
var details = [ { studentId: 10, marks: 75, studentName: "John" }, { studentId: 10, marks: 75, studentName: "John" }, { studentId: 11, marks: 98, studentName: "Bob" } ]; output = Object.values(details.reduce((value, object) => { if (value[object.studentId]) { ['marks'].forEach(key => value[object.studentId][key] = value[object.studentId][key] + object[key]); } else { value[object.studentId] = { ...object }; } return value; }, {})); console.log(output);
To run the above program, use the following command −
node fileName.js.
Here, my file name is demo237.js.
Output
The output is as follows −
PS C:\Users\Amit\javascript-code> node demo237.js [ { studentId: 10, marks: 150, studentName: 'John' }, { studentId: 11, marks: 98, studentName: 'Bob' } ]
- Related Articles
- What is the best way to initialize a JavaScript number?
- The best way to remove duplicates from an array of objects in JavaScript?
- What is the best way to initialize a JavaScript Date to midnight?
- What is the best way to concatenate strings in JavaScript?
- What is the best way to convert a number to a string in JavaScript?
- What is the best way to compare two strings in JavaScript?
- What is the best way to add an event in JavaScript?
- What is the best way of declaring multiple Variables in JavaScript?
- What is the best way to handle a Javascript popup using Selenium Webdriver?
- What is the best way to do optional function parameters in JavaScript?
- What is the best way to break from nested loops in JavaScript?
- Can I extend a JavaScript error? What is the best way to do so?
- How to merge two JavaScript objects?
- What is the best way to log a Python exception?
- What is 3-way merge or merge commit in Git?

Advertisements