I have the following code which takes an array that might have duplicate id
s and will merge the items
of those duplicate, and keep only one element per id which contains all the items of all elements with the same id.
array = [{
id: 1,
items: [1, 2, 3]
},
{
id: 2,
items: [1, 2]
},
{
id: 1,
items: [4]
},
{
id: 3,
items: [1]
},
];
const mergeLines = (a) => {
const processedIds = [];
const finalResult = [];
a.forEach((element) => {
const elementId = element.id;
if (processedIds.indexOf(elementId) === -1) {
const occurences = a.filter((el) => el.id === elementId);
if (occurences.length > 1) {
const allItems = occurences.reduce((acc, curr) => {
acc = acc.concat(curr.items);
return acc;
}, []);
element = { ...element,
items: allItems
};
finalResult.push(element);
} else {
finalResult.push(element);
}
processedIds.push(elementId);
}
});
return finalResult;
};
console.log(mergeLines(array));
I feel this code can be optimized much further to 0(n)