Skip to content

Instantly share code, notes, and snippets.

@farhad-taran
Created November 18, 2021 16:46
Show Gist options
  • Save farhad-taran/dce29524a956cb040f101654028680db to your computer and use it in GitHub Desktop.
Save farhad-taran/dce29524a956cb040f101654028680db to your computer and use it in GitHub Desktop.
GroupBy in javascript

some scenarios require us to group objects if a certain property of those objects match. the following js function using the reduce method mimics this behaviour.

function groupBy(list, field) {
  const groups = list.reduce((groups, item) => {
    const group = (groups[item[field]] || []);
    group.push(item);
    groups[item[field]] = group;
    return groups;
  }, []);
  return Object.keys(groups).map(key => groups[key]);
}

usage:

  const objects = [{
    id: 'some'
  },
  {
    id: 'other'
  },
  {
    id: 'some'
  }];

const grouped = groupBy(objects, 'id');

the above will give you an array of arrays:

  [
    [
      {
        id: 'some'
      },
      {
        id: 'some'
      },
    ],
    [
      {
        id: 'other'
      }
    ]
  ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment