Created
September 25, 2018 15:07
-
-
Save ramsunvtech/102ac0267d33c2cc1ccdf9158d0f7fca to your computer and use it in GitHub Desktop.
Group By - ES6
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
function groupBy(list, props) { | |
return list.reduce((a, b) => { | |
(a[b[props]] = a[b[props]] || []).push(b); | |
return a; | |
}, {}); | |
} | |
// Usage. | |
groupBy([{ | |
id: 1, | |
group: 'user', | |
name: 'User #1', | |
}, { | |
id: 2, | |
group: 'admin', | |
name: 'User #2', | |
}, { | |
id: 3, | |
group: 'moderator', | |
name: 'User #3', | |
}, { | |
id: 4, | |
group: 'user', | |
name: 'User #4', | |
}, { | |
id: 5, | |
group: 'moderator', | |
name: 'User #5', | |
}], 'group'); | |
/* | |
{admin: [], user: [], moderator: []} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment