Skip to content

Instantly share code, notes, and snippets.

@dhwang
Created May 24, 2024 23:50
Show Gist options
  • Save dhwang/4cb741a567f7e20ba777688f4df06b8d to your computer and use it in GitHub Desktop.
Save dhwang/4cb741a567f7e20ba777688f4df06b8d to your computer and use it in GitHub Desktop.
uniqueBy
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