-2

I have this data.

const data = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 6 },
{ id: 6 },
{ id: 6 },
{ id: 7 },
{ id: 8 },
{ id: 8 },
{ id: 8 },
{ id: 8 }
];

and I want to filter it and remove all the objects with duplicate id. It should look like this.

const data = [
 { id: 1 },
 { id: 2 },
 { id: 3 },
 { id: 4 },
 { id: 5 },
 { id: 6 },
 { id: 7 },
 { id: 8 }
 ];

I think I need to do with filter method but not sure how to achieve this.

Samyog Dhital
  • 35
  • 1
  • 9
  • 1
    You can look this comment, this is using for loop and for condition https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects/71202895#71202895 – Fajrul Aulia Feb 21 '22 at 07:59

1 Answers1

0

you can try it:

const data = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 6 },
{ id: 6 },
{ id: 6 },
{ id: 7 },
{ id: 8 },
{ id: 8 },
{ id: 8 },
{ id: 8 }
];

var result = data.reduce((unique, o) => {
    if(!unique.some(obj => obj.id === o.id)) {
      unique.push(o);
    }
    return unique;
},[]);
console.log(result);

improve => for run-time complexity of O(n):

const data = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 6 },
{ id: 6 },
{ id: 6 },
{ id: 7 },
{ id: 8 },
{ id: 8 },
{ id: 8 },
{ id: 8 }
];
var result = Object.values(data.reduce((acc,cur)=>Object.assign(acc,{[cur.id]:cur}),{}))
console.log(result);
  • 1
    This has run-time complexity of O(n²), but it’s possible to do this in O(n), e.g. like this answer: [How to remove all duplicates from an array of objects?](/a/50082488/4642212). In that answer, `cur.id` only considers the ID, which is sufficient for this case. – Sebastian Simon Feb 21 '22 at 08:17