DEV Community

Julio Aguilar
Julio Aguilar

Posted on

How do I group an array of objects in JavaScript and sum a field?

import { groupBy } from 'groupjs_by';

const byStatus = groupBy(orders, 'status')
  .sum('revenue', 'amount')
  .count('orders')
  .toArray();
Enter fullscreen mode Exit fullscreen mode

bash

npm install groupjs_by
Enter fullscreen mode Exit fullscreen mode

Every modern article tells you to use native Object.groupBy(). The problem? It stops halfway. Native bucketing only splits your data into isolated arrays. It leaves you stuck writing messy reduce() loops just to figure out a basic sum, average, or count.

// Native Object.groupBy(): Only creates buckets. You still have to loop.
const buckets = Object.groupBy(orders, o => o.status);
const result = Object.keys(buckets).map(status => ({
  status,
  revenue: buckets[status].reduce((sum, o) => sum + o.amount, 0),
  orders: buckets[status].length
}));

// groupjs_by: Groups AND aggregates in a single, fast pass.
const result = groupBy(orders, 'status').sum('revenue', 'amount').count('orders').toArray();
Enter fullscreen mode Exit fullscreen mode

If you are building dashboards, reporting pipelines, or handling metrics, here are two common patterns you can grab right now.

Multi-Key Grouping (Two Dimensions)
Need to group by country and status at the same time? Instead of writing nested loops, pass an array of keys. Calling .toArray() formats the results into flat, chart-ready rows.

You can pass an array of keys for multi-key dimensions like country and status, or use accessor functions for nested JSON data. For full code examples, multi-key implementations, nested JSON accessor patterns, and benchmarks, check the repository.

Zero Dependencies. Built for Performance.

  • Single-Pass Aggregation: .aggregate() runs math operations concurrently to scan large datasets efficiently.
  • Safe Loops: Avoids call-stack overflows on giant arrays (100k+ rows).
  • Data Hygiene: Skips null, undefined, or corrupted non-numeric fields automatically so your math never breaks into NaN.

Check out the full documentation, TypeScript examples, and performance benchmarks on GitHub:

groupBy

Drop a star ⭐ if this saves you from writing another boilerplate reduce loop!

Top comments (0)