Skip to content

Instantly share code, notes, and snippets.

@lmfresneda
Last active January 17, 2021 15:36
Show Gist options
  • Save lmfresneda/9158e06a93a819a78b30cc175573a8d3 to your computer and use it in GitHub Desktop.
Save lmfresneda/9158e06a93a819a78b30cc175573a8d3 to your computer and use it in GitHub Desktop.
Remove duplicates from an array of objects in javascript
// FUN METHOD
/**
* Remove duplicates from an array of objects in javascript
* @param arr - Array of objects
* @param prop - Property of each object to compare
* @returns {Array}
*/
function removeDuplicates( arr, prop ) {
let obj = {};
return Object.keys(arr.reduce((prev, next) => {
if(!obj[next[prop]]) obj[next[prop]] = next;
return obj;
}, obj)).map((i) => obj[i]);
}
// FUN METHOD COMPRESSED - 147 bytes
/*
function removeDuplicates(e,n){var o={};return Object.keys(e.reduce(function(e,r){return o[r[n]]||(o[r[n]]=r),o},o)).map(function(e){return o[e]})}
*/
// MORE EFFICIENT, BUT LESS FUN
/**
* Remove duplicates from an array of objects in javascript
* @param arr - Array of objects
* @param prop - Property of each object to compare
* @returns {Array}
*/
function removeDuplicates( arr, prop ) {
var obj = {};
for ( var i = 0, len = arr.length; i < len; i++ ){
if(!obj[arr[i][prop]]) obj[arr[i][prop]] = arr[i];
}
var newArr = [];
for ( var key in obj ) newArr.push(obj[key]);
return newArr;
}
// MORE EFFICIENT, BUT LESS FUN COMPRESSED - 143 bytes
/*
function removeDuplicates(e,r){for(var n={},o=0,t=e.length;t>o;o++)n[e[o][r]]||(n[e[o][r]]=e[o]);var u=[];for(var c in n)u.push(n[c]);return u}
*/
@nwaughachukwuma
Copy link

I guess ES6 way is more fun using set and spread.

let removeDuplicates = newArray => [...new Set(newArray)];

Then just use:

removeDuplicates(yourArray);

Read here about performance

@awran5, thanks for the more concise approach. But does this do a deep comparison on an array of objects? I don't think so...

@evory
Copy link

evory commented Jan 15, 2019

Thank you ! Works nice

Copy link

ghost commented Feb 25, 2019

Thank you!!!

@kausha15
Copy link

kausha15 commented Jun 3, 2019

After searching a lot, finally got a solution which is simple and efficient!
Kudos to you

@RamsesMartinez
Copy link

I guess ES6 way is more fun using set and spread.

let removeDuplicates = newArray => [...new Set(newArray)];

Then just use:

removeDuplicates(yourArray);

Read here about performance

oddly it didn't work for me

@paragopinath
Copy link

paragopinath commented Jul 4, 2020

I guess ES6 way is more fun using set and spread.

let removeDuplicates = newArray => [...new Set(newArray)];

Then just use:

removeDuplicates(yourArray);

Read here about performance

@awran5 Works like charm for my use case! Thank you!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment