-
-
Save lmfresneda/9158e06a93a819a78b30cc175573a8d3 to your computer and use it in GitHub Desktop.
// 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} | |
*/ |
Thanks bro. They had told us to remove duplicates from an array of JSON objects without using any loops. So the first on workerd
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
Thanks a lot!!
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...
Thank you ! Works nice
Thank you!!!
After searching a lot, finally got a solution which is simple and efficient!
Kudos to you
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
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!!!
Nice! Helped me a lot. Thank you!