I have this array of objects:
const arrayOfObjects = [{
id: 10,
children: [1000]
},
{
id: 10,
children: [2000]
},
{
id: 20,
children: [1000]
},
{
id: 20,
children: [1000, 2000]
},
{
id: 20,
children: [2000]
},
];
I want to remove duplicates using this code:
const arrayHashMap = arrayOfObjects.reduce((obj, item) => {
if (obj[item.id]) {
// obj[item.id].children.push(...item.children);
const temporaryArray = [...obj[item.id].children, ...item.children];
obj[item.id].children = [...new Set(temporaryArray)];
} else {
obj[item.id] = {
...item
};
}
return obj;
}, {});
const result = Object.values(arrayHashMap);
In this code I commented part where I push values to array. I tried to use "new Set" to remove duplicates from final array, but I am always assigning the value to "obj[item.id].children". Is this OK or is there a better way to write this?
Expected result:
[{
id: 10,
children: [1000, 2000]
}, {
id: 20,
children: [1000, 2000]
}]
Thanks