Skip to content

Instantly share code, notes, and snippets.

@RedRoserade
Created July 30, 2015 13:48
Show Gist options
  • Save RedRoserade/705229ad129176894c5c to your computer and use it in GitHub Desktop.
Save RedRoserade/705229ad129176894c5c to your computer and use it in GitHub Desktop.
[ES6] Return distinct items in an iterable by using a specific key selector for equality checking. Only the first item of each key is returned.
function* distinctBy(iterable, keySelector) {
const keys = new Set();
for (const item of iterable) {
const key = keySelector(item);
if (!keys.has(key)) {
keys.add(key);
yield item;
}
}
}
const items = [
{ id: 1, name: 'André' },
{ id: 2, name: 'Filipe' },
{ id: 2, name: 'Paulo' } // will be ignored
];
console.log(Array.from(distinctBy(items, i => i.id)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment