Skip to content

Group array items by property with Object.groupBy and Map.groupBy

JavaScript Dasun Kalupahana 108 views

const people = [
  { name: "Ann", role: "dev" },
  { name: "Bob", role: "ops" },
  { name: "Cy", role: "dev" },
];
console.log(Object.groupBy(people, p => p.role));
console.log(Map.groupBy(people, p => p.role).get("ops"));
// [Object: null prototype] {
//   dev: [ { name: 'Ann', role: 'dev' }, { name: 'Cy', role: 'dev' } ],
//   ops: [ { name: 'Bob', role: 'ops' } ]
// }
// [ { name: 'Bob', role: 'ops' } ]

Buckets an array by a callback’s return value, replacing the usual reduce boilerplate. Map.groupBy keeps non-string keys. The Object.groupBy result has a null prototype. Needs Node 21+, Chrome 117, Firefox 119 or Safari 17.4.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.