Group an array by a key

Object.groupBy is finally a thing. Here it is, with the fallback for older runtimes.

SNP 056 #496 Filed js

javascript
const byTag = Object.groupBy(posts, (post) => post.tag)
// { webdev: [...], gamedev: [...] }

It's in all current browsers and Node 21+. Map.groupBy does the same but returns a Map, which you want when the keys aren't strings.

Where you can't rely on it yet, the reduce version is a few lines:

javascript
const groupBy = (items, key) =>
  items.reduce((groups, item) => {
    const k = key(item)
    groups[k] ??= []
    groups[k].push(item)
    return groups
  }, {})