Skip to content

Instantly share code, notes, and snippets.

@fvilante
Last active June 27, 2019 19:56
Show Gist options
  • Save fvilante/74f702cfe809959e6ec169ea453816fc to your computer and use it in GitHub Desktop.
Save fvilante/74f702cfe809959e6ec169ea453816fc to your computer and use it in GitHub Desktop.
groupBy
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