Group an array by a key

Build an object of arrays with reduce (works everywhere, unlike Object.groupBy).

javascript beginner #arrays#data#objects
Apri nel playground
js-group-by.js
const orders = [
  { customer: "ada", total: 30 },
  { customer: "linus", total: 12 },
  { customer: "ada", total: 8 },
];

const byCustomer = orders.reduce((acc, order) => {
  (acc[order.customer] ||= []).push(order);
  return acc;
}, {});

console.log(byCustomer);