
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Reduce Array While Merging a Field 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' ] } ]
Advertisements