Created
May 24, 2019 21:25
-
-
Save leobalter/7003bb0c1633a44743d50619993ad226 to your computer and use it in GitHub Desktop.
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
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