Skip to content

Instantly share code, notes, and snippets.

@leobalter leobalter/uniqBy.js
Created May 24, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.