Remove duplicates from JavaScript Array based on Object Properties


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

let p = [{
 id: '0923482304',
 name: 'Some super nasheed'
 {  id: '0923482304',
 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 = =>; // to get an array of just the ids, or whichever property we'd like to filter with.
if(array_ids.indexOf( === 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) => => == index);

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


1 comment

Leave a Reply

960 people have read this article.