Skip to content

Instantly share code, notes, and snippets.

@surajp
Last active March 31, 2020 21:07
Show Gist options
  • Save surajp/b87689d69e781a1927b31a892d7a9cb5 to your computer and use it in GitHub Desktop.
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
/** 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