Created
May 24, 2024 23:50
-
-
Save dhwang/4cb741a567f7e20ba777688f4df06b8d to your computer and use it in GitHub Desktop.
uniqueBy
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
const uniqBy = (arr, predicate) => { | |
if (!Array.isArray(arr)) { return []; } | |
const cb = typeof predicate === 'function' ? predicate : (o) => o[predicate]; | |
const pickedObjects = arr | |
.filter(item => item) | |
.reduce((map, item) => { | |
const key = cb(item); | |
if (!key) { return map; } | |
return map.has(key) ? map : map.set(key, item); | |
}, new Map()) | |
.values(); | |
return [...pickedObjects]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment