Skip to content

Instantly share code, notes, and snippets.

@leobalter
Created May 24, 2019 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leobalter/7003bb0c1633a44743d50619993ad226 to your computer and use it in GitHub Desktop.
Save leobalter/7003bb0c1633a44743d50619993ad226 to your computer and use it in GitHub Desktop.
function uniqBy(iter, mapFn) {
var map = new Map();
for (let item of iter) {
let key = mapFn(item);
// Use the first given key identifier
if (map.has(key)) {
continue;
}
map.set(key, item);
}
return map;
}
// Tests
var obj1 = {
id: 1,
name: 'Leo'
};
var obj2 = {
id: 2,
name: 'Felipe'
};
var obj3 = {
id: 1,
name: 'Jaydson'
};
var obj4 = {
id: 3,
name: 'Leo'
};
var arr = [obj1, obj2, obj3, obj4, obj1];
var result;
result = uniqBy(arr, x => x.id);
console.log(Array.from(result.values()));
// expects:
// [
// { id: 1, name: 'Leo' },
// { id: 2, name: 'Felipe' },
// { id: 3, name: 'Leo' }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment