

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to reduce an array while merging one of its field as well in JavaScript
Consider, we have the following array of objects −
const arr = [{ id: 121, hobby: 'cycling' }, { id: 125, hobby: 'jogging' }, { id: 129, hobby: 'reading' }, { id: 121, hobby: 'writing' }, { id: 121, hobby: 'playing football' }, { id: 125, hobby: 'cooking' }, { id: 129, hobby: 'horse riding' }];
Let’s say, we have to write a function that takes in such an array and merges it based on the common id property, and for the hobby property we assign it an array and put all hobbies for specific ids in there.
We will use the Array.prototype.reduce() method to iterate over the array and merge entries with the same indices at the same time.
The code for doing this will be −
Example
const arr = [{ id: 121, hobby: 'cycling' }, { id: 125, hobby: 'jogging' }, { id: 129, hobby: 'reading' }, { id: 121, hobby: 'writing' }, { id: 121, hobby: 'playing football' }, { id: 125, hobby: 'cooking' }, { id: 129, hobby: 'horse riding' }]; const mergeArray = (arr) => { return arr.reduce((acc, val) => { const ind = acc.findIndex(item => item.id === val.id); if(ind !== -1){ acc[ind].hobby.push(val.hobby); }else{ acc.push({ id: val.id,hobby: [val.hobby] }); }; return acc; }, []); }; console.log(mergeArray(arr));
Output
The output in the console will be −
[ { id: 121, hobby: [ 'cycling', 'writing', 'playing football' ] }, { id: 125, hobby: [ 'jogging', 'cooking' ] }, { id: 129, hobby: [ 'reading', 'horse riding' ] } ]
- Related Questions & Answers
- Reduce an array to groups in JavaScript
- Merging two sorted arrays into one sorted array using JavaScript
- JavaScript Auto-filling one field same as other
- Java regular expression program to validate an email including blank field valid as well
- Encoding string to reduce its size in JavaScript
- Reduce array in JavaScript
- Reduce an array to the sum of every nth element - JavaScript
- Return the Lower triangle of an array and zero the main diagonal as well in Numpy
- Return the Upper triangle of an array and zero the main diagonal as well in Numpy
- Comparing forEach() and reduce() for summing an array of numbers in JavaScript.
- Merging boolean array with AND operator - JavaScript
- Set options while creating a MySQL table. Display the same options as well
- How to convert array into array of objects using map() and reduce() in JavaScript
- Reduce decimals while printing in Arduino
- Reduce array's dimension by one in Numpy
Advertisements