Skip to content

Instantly share code, notes, and snippets.

@nkhil
Last active November 8, 2019 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkhil/6976de57f5feff524c7cc98c5452e770 to your computer and use it in GitHub Desktop.
Save nkhil/6976de57f5feff524c7cc98c5452e770 to your computer and use it in GitHub Desktop.
Group Array of JavaScript Objects by Key or Property Value

How to group an array of JavaScript objects by key or property value

I first came across this code on JamieMason's gist. Here I've tried to re-create it from scratch as I found their solution slightly hard to follow.

Implementation

function groupBy(key) {
  return function group(array) {
    return array.reduce((acc, obj) => {
      const property = obj[key];
      acc[property] = acc[property] || [];
      acc[property].push(obj);
      return acc;
    }, {});
  }
}

Usage

const dogs = [
  { name: 'Biscuit', age: '23', 'color': 'black '},
  { name: 'Diamond', age: '21', 'color': 'white '},
  { name: 'Oreo', age: '20', 'color': 'yellow '},
  { name: 'Zelda', age: '19', 'color': 'red'},
  { name: 'Snuggles', age: '23', 'color': 'red '},
  { name: 'Ron Burgandy', age: '23', 'color': 'black '},
];

const groupByAge = groupBy('age');
console.log(groupByAge(dogs));

Output

{
  '19': [ { name: 'Zelda', age: '19', color: 'red' } ],
  '20': [ { name: 'Oreo', age: '20', color: 'yellow ' } ],
  '21': [ { name: 'Diamond', age: '21', color: 'white ' } ],
  '23': [
    { name: 'Biscuit', age: '23', color: 'black ' },
    { name: 'Snuggles', age: '23', color: 'red ' },
    { name: 'Ron Burgandy', age: '23', color: 'black ' }
  ]
}

P.S. I'm aware that most dogs don't live to be 23 years old. RIP biscuit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment