Skip to content

Instantly share code, notes, and snippets.

@brianmcallister
Created June 17, 2020 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianmcallister/9d7365b5449236929a0a580572a35aca to your computer and use it in GitHub Desktop.
Save brianmcallister/9d7365b5449236929a0a580572a35aca to your computer and use it in GitHub Desktop.
Unique list of JavaScript objects.
interface Item {
type: string;
}
const listA: Item[] = [
{ type: 'a' },
{ type: 'b' },
{ type: 'c' },
];
const listB: Item[] = [
{ type: 'a' },
{ type: 'b' },
];
const listC: Item[] = [
{ type: 'b' },
{ type: 'c' },
{ type: 'd' },
];
const uniqueByKey = <T extends object, U extends keyof T>(key: U, ...items: T[][]) => {
const flat = items.reduce((acc, next) => ([...acc, ...next]), []);
const keys = [...new Set(flat.map(item => item[key]))];
return keys.map(flatKey => flat.find(item => item[key] === flatKey));
}
console.log('unique objects:');
console.table(uniqueByKey('type', listA, listB, listC));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment