Emmanuel Akinfulubi

JavaScriptBasic

Group an array of objects by key in JavaScript

Intermediate · 4 min read

Grouping a list by one of its fields is one of the most useful things you can do with data. A list of orders grouped by customer. Students grouped by class. Expenses grouped by month. Once the records are grouped, you can show them under headings, count them or total them.

In this tutorial you will write groupBy(items, keyOf), which takes a list of objects and a function that picks the field to group by, and returns a Map from each value to the records that share it. Then you will see that counting by a field, countBy, is the same function with a number instead of a list. You need to know what an array, an object and an arrow function are.

The data

The examples use a small list of buses. Each one has a plate number, a route and a tier:

JavaScript

const buses = [
  { plate: 'LAG-441-XA', route: 'Lagos - Abuja', tier: 'luxury' },
  { plate: 'ABJ-772-KM', route: 'Lagos - Abuja', tier: 'economy' },
  { plate: 'ENU-318-PH', route: 'Lagos - Kano', tier: 'luxury' },
  { plate: 'KAN-905-BD', route: 'Lagos - Kano', tier: 'economy' },
];
console.log(buses.length); // 4

Grouping by route should give two groups, 'Lagos - Abuja' and 'Lagos - Kano', with two buses in each.

What a Map is

A Map stores pairs: a key you look things up by, and a value stored under it. set(key, value) stores, get(key) reads back (or gives undefined if the key isn't there), and size counts the keys.

JavaScript

const groups = new Map();
groups.set('Lagos - Abuja', ['LAG-441-XA']);
console.log(groups.get('Lagos - Abuja')); // [ 'LAG-441-XA' ]
console.log(groups.get('Lagos - Jos'));   // undefined
console.log(groups.size);                 // 1

For grouping, each key is a field value and each value is an array of records, often called a bucket.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

38 Group a list by a key

fair

Take a list of records and group them by one of their fields, so you can look up all the records sharing a value.

Stuck? Three hints, smallest first
  1. 1. A Map keyed by the field value, holding arrays, is the natural shape.
  2. 2. map.get(key) ?? [] then push is the usual idiom for building it.
  3. 3. Modern engines have Object.groupBy and Map.groupBy; write it yourself first.

Step 1: one bucket per key

For each item, work out its key. Get that key's bucket, or start an empty one if this is the first item with that key. Add the item and store the bucket back:

JavaScript

const buses = [
  { plate: 'LAG-441-XA', route: 'Lagos - Abuja' },
  { plate: 'ABJ-772-KM', route: 'Lagos - Abuja' },
  { plate: 'ENU-318-PH', route: 'Lagos - Kano' },
];
const byRoute = new Map();
for (const bus of buses) {
  const bucket = byRoute.get(bus.route) ?? [];
  bucket.push(bus);
  byRoute.set(bus.route, bucket);
}
console.log(byRoute.size);                        // 2
console.log(byRoute.get('Lagos - Abuja').length); // 2

?? means "use the left side unless it is null or undefined, in which case use the right side". So byRoute.get(bus.route) ?? [] reads as "the existing bucket, or a new empty one".

Step 2: make the key a function

That loop only groups by route. To group by anything, pass in a function, keyOf, that takes an item and returns its key:

Step 2

function groupBy(items, keyOf) {
  const out = new Map();
  for (const item of items) {
    const key = keyOf(item);
    const bucket = out.get(key) ?? [];
    bucket.push(item);
    out.set(key, bucket);
  }
  return out;
}
const buses = [
  { plate: 'LAG-441-XA', route: 'Lagos - Abuja', tier: 'luxury' },
  { plate: 'ABJ-772-KM', route: 'Lagos - Abuja', tier: 'economy' },
  { plate: 'ENU-318-PH', route: 'Lagos - Kano', tier: 'luxury' },
  { plate: 'KAN-905-BD', route: 'Lagos - Kano', tier: 'economy' },
];
const byRoute = groupBy(buses, (b) => b.route);
const byTier = groupBy(buses, (b) => b.tier);
console.log(byRoute.get('Lagos - Kano').map((b) => b.plate)); // [ 'ENU-318-PH', 'KAN-905-BD' ]
console.log(byTier.get('luxury').length);                     // 2

The same function now groups by route or by tier. A function key is more flexible than a field name, because the key can be computed. For example, (b) => b.plate.slice(0, 3) groups by the first three letters of the plate.

Step 3: walk through the groups

A for...of loop over a Map gives you each [key, value] pair. Unpacking them with [route, list] names both parts:

JavaScript

for (const [route, list] of byRoute) {
  console.log(route, '->', list.map((b) => b.plate).join(', '));
}
// Lagos - Abuja -> LAG-441-XA, ABJ-772-KM
// Lagos - Kano -> ENU-318-PH, KAN-905-BD

A Map keeps its keys in the order they were first added, so the groups appear in the order their first record appeared.

Step 4: counting is the same shape

Often you only need how many in each group. Store a number instead of an array: the count so far, or 0, plus 1.

Step 4

function countBy(items, keyOf) {
  const out = new Map();
  for (const item of items) out.set(keyOf(item), (out.get(keyOf(item)) ?? 0) + 1);
  return out;
}
console.log([...countBy(buses, (b) => b.tier).entries()]); // [ [ 'luxury', 2 ], [ 'economy', 2 ] ]

entries() gives every pair, and spreading them into an array makes them easy to print or compare.

Built-in versions

Newer JavaScript engines include Object.groupBy and Map.groupBy, which do the same job as Step 2:

JavaScript

const groups = Map.groupBy([1, 2, 3, 4], (n) => (n % 2 === 0 ? 'even' : 'odd'));
console.log(groups.get('even')); // [ 2, 4 ]

They are worth knowing, but writing groupBy yourself first is how you learn the pattern. It is also the version to use if your code has to run somewhere that doesn't have them yet.

The full solution

The complete answer groups the buses by route and by tier, prints each route's plates, counts the buses per tier, and checks an unknown key and an empty list. Press Run to see the output.

The answer

const buses = [
  { plate: 'LAG-441-XA', route: 'Lagos - Abuja', tier: 'luxury' },
  { plate: 'ABJ-772-KM', route: 'Lagos - Abuja', tier: 'economy' },
  { plate: 'ENU-318-PH', route: 'Lagos - Kano', tier: 'luxury' },
  { plate: 'KAN-905-BD', route: 'Lagos - Kano', tier: 'economy' },
];

function groupBy(items, keyOf) {
  const out = new Map();
  for (const item of items) {
    const key = keyOf(item);
    const bucket = out.get(key) ?? [];
    bucket.push(item);
    out.set(key, bucket);
  }
  return out;
}

const byRoute = groupBy(buses, (b) => b.route);
const byTier = groupBy(buses, (b) => b.tier);

for (const [route, list] of byRoute) {
  console.log(route, '->', list.map((b) => b.plate).join(', '));
}

// Counting is the same shape with a number instead of an array.
function countBy(items, keyOf) {
  const out = new Map();
  for (const item of items) out.set(keyOf(item), (out.get(keyOf(item)) ?? 0) + 1);
  return out;
}

console.log('per tier:', [...countBy(buses, (b) => b.tier).entries()]);

Output


      
7 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('two routes', byRoute.size, 2);
test('two buses on the Abuja run', byRoute.get('Lagos - Abuja').length, 2);
test('the right plates', byRoute.get('Lagos - Kano').map((b) => b.plate), ['ENU-318-PH', 'KAN-905-BD']);
test('grouped by tier instead', byTier.get('luxury').length, 2);
test('an unknown key is undefined', byRoute.get('Lagos - Jos'), undefined);
test('counting by tier', [...countBy(buses, (b) => b.tier).entries()], [['luxury', 2], ['economy', 2]]);
test('an empty list groups to nothing', groupBy([], (x) => x).size, 0);

groupBy and countBy are the same five lines with an array or a number in the bucket, and between them they cover a large share of everyday data work. Passing the key as a function rather than a field name is what makes it reusable: you can group by anything computed, not just by a property that already exists.

Common mistakes

  • Forgetting the empty-bucket fallback. out.get(key).push(item) crashes the first time a key appears, because get returns undefined.
  • Grouping into a plain object without care. Keys like constructor already exist on {}. A Map starts genuinely empty.
  • Hard-coding the field name. A keyOf function lets the same groupBy group by anything, including computed values.

Try it yourself

  1. Group the numbers 1 to 20 by their last digit.
  2. Write sumBy(items, keyOf, valueOf) that totals a field per group, such as the price of orders per customer.
  3. Write indexBy(items, keyOf) that stores one item per key instead of an array, for quick lookup by plate number.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.