Skip to content

Instantly share code, notes, and snippets.

@amit08255
Forked from lmfresneda/remove_duplicates.js
Created June 5, 2020 05:05
Show Gist options
  • Save amit08255/565244a13c9cc5079ffc013219c49186 to your computer and use it in GitHub Desktop.
Save amit08255/565244a13c9cc5079ffc013219c49186 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}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment