Skip to content

Instantly share code, notes, and snippets.

@xadamxk
Created September 13, 2021 18:46
Show Gist options
  • Save xadamxk/b290027348df83dc933ecb0bbfbf6151 to your computer and use it in GitHub Desktop.
Save xadamxk/b290027348df83dc933ecb0bbfbf6151 to your computer and use it in GitHub Desktop.
Javascript: Group Array of Objects By Property
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