Removing duplicates in Array of Objects
by marek8623
HTML
<button>
Click me
</button>
JavaScript
$('button')
.html('Click me')
.on('click', () => example())
const arrayOfObjects = [{
id: 10,
children: [1000]
},
{
id: 10,
children: [2000]
},
{
id: 20,
children: [1000]
},
{
id: 20,
children: [1000, 2000]
},
{
id: 20,
children: [2000]
},
]
const example = () => {
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);
console.log(result);
};