Home > Enterprise >  How to remove data with same id in an array of object using javascript?
How to remove data with same id in an array of object using javascript?

Time:11-15

in an arry of objects i want to remove object which have same id (duplicated data) using javascript.

below is the input array

const input = [
    {
         id: '1',
         name: 'first',
    },
    {  
         id: '1',
         name: 'first',
    },
    { 
         id: '2',
         name: 'second',
    },
    {
         id: '2',
         name: 'second',
    }, 
]

so as you see from above array there are duplicating data with id '1' and '2'. if there is similar id i want include only one

so the expected output is like below,

const output = [
    {
        id: '1',
        name: 'first',
    },
    {
        id: '2',
        name: 'second',
    },
]

how can i do this. could someone help me with this. i am new to programming thanks.

CodePudding user response:

You can use reduce to filter data from the array based on some condition like bellow

const input = [
    {
         id: '1',
         name: 'first',
    },
    {  
         id: '1',
         name: 'first',
    },
    { 
         id: '2',
         name: 'second',
    },
    {
         id: '2',
         name: 'second',
    }, 
]

const result = input.reduce((accumulator, current) => {
  let exists = accumulator.find(item => {
    return item.id === current.id;
  });
  if(!exists) { 
    accumulator = accumulator.concat(current);
  }
  return accumulator;
}, []);

console.log(result);

CodePudding user response:

Similar to this answer. You will have to change the const to let while declaring input though, or use a new variable I suppose.

filtered_input = input.filter((value, index, self) =>
  index === self.findIndex((t) => (
    t.id === value.id
  ))
)

CodePudding user response:

you could use Set to get rid of the duplicate data like this

const input = [
    {
         id: '1',
         name: 'first',
    },
    {  
         id: '1',
         name: 'first',
    },
    { 
         id: '2',
         name: 'second',
    },
    {
         id: '2',
         name: 'second',
    }, 
]

const result = [...new Set(input.map(JSON.stringify))].map(JSON.parse)
console.log(result)

CodePudding user response:

Below is another approach

const input = [
{
     id: '1',
     name: 'first',
},
{  
     id: '1',
     name: 'first',
},
{ 
     id: '2',
     name: 'second',
},
{
     id: '2',
     name: 'second',
}, 
];
const uniqueIds = new Set();
const uniqueList = input.filter(element => {
const isDuplicate = uniqueIds.has(element.id);
  uniqueIds.add(element.id);
  return !isDuplicate;
});
console.log(uniqueList);

  • Related