Skip to content

How to group ID’s for duplicate object and remove object in array using javascript

I want to remove duplicate object from array after grouping duplicate object id from matched(already existing) object id. Whatever i have tried that’s grouping ID’s but not getting how to remove duplicate object from array.

Original Array

        [
         {id:2,title:'men'},
         {id:3,title:'women'},
         {id:1,title:'kids'},
         {id:4,title:'sports'}, 
         {id:5, title:'women'},
         {id:6,title:'kids'}
       ];

Expected Array

 [
   { id: 2, title: 'men' },
   { id: [3,5], title: 'women' },
   { id: [1,6], title: 'kids' },
   { id: 4, title: 'sports' }
 ]

Tried

let array = [{id:2,title:'men'},{id:3,title:'women'},{id:1,title:'kids'},
{id:4,title:'sports'}, {id:5, title:'women'},{id:6,title:'kids'}];

for(let i=0; i<array.length-1;i++){
    for(let j=i+1; j<array.length; j++){
        if(array[i].title===array[j].title)
         array[i]={id:[array[i].id, array[j].id], title: array[i].title}
    }
}
console.log(array)

Please help to achieve expected result in better way.

Answer

let items = [{
        id: 2,
        title: 'men'
    },
    {
        id: 3,
        title: 'women'
    },
    {
        id: 1,
        title: 'kids'
    },
    {
        id: 4,
        title: 'sports'
    },
    {
        id: 5,
        title: 'women'
    },
    {
        id: 6,
        title: 'kids'
    }
];

let dest = [];

items.forEach(x => {
    let find;
    if (find = dest.find(y => y.title === x.title)) {
        find.id = Array.isArray(find.id) ? [...find.id, x.id] : [find.id, x.id]
    } else {
        dest.push(x)
    }
})

console.log(dest)