Group an array by a key

Javascript

Object.groupBy is available in current runtimes; the reduce version is the fallback for older ones.

const byStatus = Object.groupBy(orders, (o) => o.status);

// Older runtimes:
const grouped = orders.reduce((acc, o) => {
  (acc[o.status] ||= []).push(o);
  return acc;
}, {});

More in JavaScript

Random picks