Last active
June 27, 2019 19:56
-
-
Save fvilante/74f702cfe809959e6ec169ea453816fc to your computer and use it in GitHub Desktop.
groupBy
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
let seniors = [ | |
{ | |
"id": 1, | |
"name": "Jack", | |
"active": true, | |
"level": "senior" | |
}, | |
{ | |
"id": 2, | |
"name": "Suzan", | |
"active": true, | |
"level": "senior" | |
}, | |
{ | |
"id": 3, | |
"name": "Joana", | |
"level": "senior", | |
"active": true | |
}, | |
{ | |
"id": 4, | |
"name": "Mark", | |
"level": "senior", | |
"active": false | |
} | |
]; | |
interface User { | |
id: number | |
name: string | |
active: boolean | |
level: Level | |
} | |
type Grouped<T> = { | |
[groupname: string]: Array<T> | |
} | |
const groupBy_ = <T extends object>(list: Array<T>, key: keyof T) => list.reduce( (acc:Grouped<T>, item:T):Grouped<T> => ( | |
{ | |
...acc, | |
[ item[key] ]: [ | |
...( acc[ item[key] ] || [ ] ), item | |
] | |
} | |
), {} /*inicial state*/ ); | |
const seniors_: Array<User> = seniors; | |
const ouput: Grouped<User> = groupBy_(seniors_, "active"); | |
// expected output -> result === output | |
const result = { | |
"true": [ | |
{ | |
"id": 1, | |
"name": "Jack", | |
"active": true, | |
"level": "senior" | |
}, | |
{ | |
"id": 2, | |
"name": "Suzan", | |
"active": true, | |
"level": "senior" | |
}, | |
{ | |
"id": 3, | |
"name": "Joana", | |
"level": "senior", | |
"active": true | |
} | |
], | |
"false": [ | |
{ | |
"id": 4, | |
"name": "Mark", | |
"level": "senior", | |
"active": false | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment