I guess I have a dead simple problem but still didn't find a solution. I have an array which looks like this:
var originalArray = [{
id: 1,
elements: [1, 2]
},
{
id: 1,
elements: [3, 4]
},
{
id: 5,
elements: ['a', 'b']
},
{
id: 5,
elements: ['c', 'd']
}, {
id: 27,
elements: []
}]
I'd like to modify it to look like this (merge by id and join elements):
newArray = [{
id: 1,
elements: [1, 2, 3, 4]
}, {
id: 5,
elements: ['a', 'b', 'c', 'd']
}, {
id: 27,
elements: []
}]
I already had multiple tries but still didn't find an elegant way of doing it.
You can create an object keyed by ID and push elements with the same ID to them, then convert back to an array. This is more efficient than looping through on every iteration for larger arrays:
var originalArray = [{
id: 1,
elements: [1, 2]
},
{
id: 1,
elements: [3, 4]
},
{
id: 5,
elements: ['a', 'b']
},
{
id: 5,
elements: ['c', 'd']
}, {
id: 27,
elements: []
}];
const arrayHashmap = originalArray.reduce((obj, item) => {
obj[item.id] ? obj[item.id].elements.push(...item.elements) : (obj[item.id] = { ...item });
return obj;
}, {});
const mergedArray = Object.values(arrayHashmap);
console.log(mergedArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With