Remove duplicates from JavaScript Array based on Object Properties

Mar
2020
31

Let's say you have a JavaScript Array that goes something like:

let p = [{
 id: '0923482304',
 someOther:'detail'
 name: 'Some super nasheed'
 },
 {  id: '0923482304',
 someOther:'which'
 name: 'Some super nasheed'},
 {  id: '0923482305',
 someOther:'could be'
 name: 'Another super nasheed'},
 {  id: '0923482305',
 someOther:'different as well.'
 name: 'Another super nasheed'}
 ];

And you'd like to remove duplicates from this array, but not looking just for the unique objects as a whole, but unique properties of objects. So for example, you'd like to remove duplicates based on 'id' property of each object in the Array.

So this can be done in many ways, one of the ways I wrote today is rather brief, here is how it goes.

We use Array.filter(). Array.filter accepts up to 3 arguments.

1. Current array item being filtered.
2. Index of this item.
3. The full array we are filtering.

So we could do something like:

let filtered = p.filter((item, index, array) => {
let array_ids = array.map(item => item.id); // to get an array of just the ids, or whichever property we'd like to filter with.
if(array_ids.indexOf(item.id) === index) {
return true; // if we return true inside Array.filter(), that item is included in the resultant array.
} else {
return false; // otherwise it is not included. Returning false will omit the current item being checked.
}
});

We can improve this a little bit better by writing it in one line like:

let filtered = p.filter((item, index, arr) => arr.map(item => item.id).indexOf(item.id) == index);

I hope this helps someone else. Please feel free to comment if I made a stupid mistake in this code.

Thanks!

Leave a Reply

94 people have read this article.