Created
June 17, 2020 15:53
-
-
Save brianmcallister/9d7365b5449236929a0a580572a35aca to your computer and use it in GitHub Desktop.
Unique list of JavaScript objects.
This file contains 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
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