Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
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
[
{ id: 121, hobby: [ 'cycling', 'writing', 'playing football' ] },
{ id: 125, hobby: [ 'jogging', 'cooking' ] },
{ id: 129, hobby: [ 'reading', 'horse riding' ] }
]
How It Works
The reduce function maintains an accumulator array. For each object, it checks if an entry with the same id already exists using findIndex(). If found, it pushes the hobby to the existing array. Otherwise, it creates a new object with the id and hobby wrapped in an array.
Alternative Approach Using Map
const mergeArrayWithMap = (arr) => {
const map = new Map();
arr.forEach(item => {
if (map.has(item.id)) {
map.get(item.id).hobby.push(item.hobby);
} else {
map.set(item.id, { id: item.id, hobby: [item.hobby] });
}
});
return Array.from(map.values());
};
console.log(mergeArrayWithMap(arr));
[
{ id: 121, hobby: [ 'cycling', 'writing', 'playing football' ] },
{ id: 125, hobby: [ 'jogging', 'cooking' ] },
{ id: 129, hobby: [ 'reading', 'horse riding' ] }
]
Conclusion
Both approaches effectively group objects by id while merging their hobby fields into arrays. The reduce method is more functional, while the Map approach offers better performance for large datasets.
