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' ] }
]

Updated on: 20-Aug-2020

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements