Created
September 13, 2021 18:46
-
-
Save xadamxk/b290027348df83dc933ecb0bbfbf6151 to your computer and use it in GitHub Desktop.
Javascript: Group Array of Objects By Property
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
const groupArrayOfObjectsByProperty = (array, property) => { | |
return array.reduce((r, a) => { | |
r[a[property]] = [...r[a[property]] || [], a]; | |
return r; | |
}, {}); | |
} | |
const array = [ | |
{type: 'dog', name: 'Henry'}, | |
{type: 'cat', name: 'Steve'}, | |
{type: 'cat', name: 'Mav'}, | |
{type: 'monkey', name: 'George'} | |
]; | |
console.log(groupArrayOfObjectsByProperty(array, "type")) | |
/* | |
{ | |
"dog":[{"type":"dog","name":"Henry"}], | |
"cat":[{"type":"cat","name":"Steve"},{"type":"cat","name":"Mav"}], | |
"monkey":[{"type":"monkey","name":"George"}]} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment