Last active
March 31, 2020 21:07
-
-
Save surajp/b87689d69e781a1927b31a892d7a9cb5 to your computer and use it in GitHub Desktop.
Remove duplicate values from an object array with an accessor function to identify dupes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Example 1: uniq([ | |
{name:'John',id:1}, | |
{name:'Jane',id:2}, | |
{name:'John',id:3}, | |
{name:'Jack',id:4} | |
],e=>e.name)= [ | |
{name:'John',id:3}, | |
{name:'Jane',id:2}, | |
{name:'Jack',id:4} | |
] | |
Example 2: uniq([ | |
{name:'John',id:1}, | |
{name:'Jane',id:2}, | |
{name:'John',id:3}, | |
{name:'Jack',id:4} | |
],e=>e.name,true)=[ | |
{name:'John',id:1}, | |
{name:'Jane',id:2}, | |
{name:'Jack',id:4} | |
] **/ | |
let uniq=(objArr,fn,useFirst)=>Object.values(objArr.reduce((collector,obj)=>{ | |
let key=fn(obj); | |
if(!useFirst || !collector[key]) | |
collector[fn(obj)]=obj; | |
return collector}, | |
{}) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment