Group an array by a key

Collect items into buckets. Object.groupBy is new, so a reduce() version is shown too.

JavaScript · Group an array by a keyIntermediate
const rows = [
  { name: 'Pen', cat: 'stationery' },
  { name: 'Lamp', cat: 'home' },
  { name: 'Ink', cat: 'stationery' },
];

const groupBy = (list, key) =>
  list.reduce((acc, item) => {
    (acc[item[key]] ||= []).push(item);
    return acc;
  }, {});

const grouped = groupBy(rows, 'cat');
// modern browsers: Object.groupBy(rows, r => r.cat)
const counts = Object.fromEntries(Object.entries(grouped).map(([k, v]) => [k, v.length]));
arraygroupreduceObject.groupBy