Emmanuel Akinfulubi

JavaScriptArray

Group array items by a key with reduce in JavaScript

Intermediate · 4 min read

Grouping means sorting a list into buckets by something the items share: orders by status, transactions by month, staff by department. You end up with an object where each key is a group name and each value is the list of items in that group. Dashboards and reports are full of this.

In this tutorial you will write groupBy with reduce, then group by a number and see what a plain object does to it. You will also meet ??=, an operator that makes the code short, and Object.groupBy, the newer built-in. You should know objects, arrays, arrow functions and the basics of reduce.

The ?? and ??= operators

a ?? b gives a, unless a is null or undefined, and then it gives b. a ??= b uses that rule to assign: it sets a to b only if a is currently null or undefined, and the whole expression gives back the value a ends up with.

JavaScript

const buckets = {};
console.log(buckets.ops ?? 'none'); // none
buckets.ops ??= [];
buckets.ops ??= ['ignored'];
console.log(buckets.ops);           // []

The second ??= does nothing, because buckets.ops already holds an array. That is exactly what you want for a bucket: create it the first time, then leave it alone.

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

33 Group a list by a key

fair

Group records into { key: [records] }. Then group by a numeric key and notice what the object did to it.

Stuck? Three hints, smallest first
  1. 1. The accumulator is an object of arrays, so create the array the first time you see a key.
  2. 2. (acc[k] ??= []).push(x) does the create-then-push in one expression.
  3. 3. A Map keyed accumulator keeps numbers as numbers; a plain object cannot.

Step 1: group by department

For each person, work out their key, make sure the bucket exists, push the person in, and return the accumulator.

Step 1

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];
const groupBy = (xs, keyOf) => xs.reduce((acc, x) => {
  (acc[keyOf(x)] ??= []).push(x);
  return acc;
}, {});
const names = (list) => list.map((s) => s.name);
const byDept = groupBy(staff, (s) => s.dept);
console.log(Object.keys(byDept)); // [ 'ops', 'eng' ]
console.log(names(byDept.ops));   // [ 'Ada', 'Chi' ]
console.log(names(byDept.eng));   // [ 'Bola', 'Dami' ]

(acc[keyOf(x)] ??= []) gives back the bucket, new or existing, and .push(x) adds the person to it. One line does "create if missing, then add".

keyOf is a function you pass in, so the same groupBy works for any key. The groups come out in the order they were first seen, and each group keeps its members in input order.

Step 2: an empty list and a missing key

Step 2

const staff = [
  { name: 'Ada', dept: 'ops' },
  { name: 'Bola', dept: 'eng' },
];
const groupBy = (xs, keyOf) => xs.reduce((acc, x) => {
  (acc[keyOf(x)] ??= []).push(x);
  return acc;
}, {});
console.log(groupBy([], (x) => x));                     // {}
console.log(Object.keys(groupBy(staff, () => undefined))); // [ 'undefined' ]

An empty list makes no groups. If the key function returns undefined, say because of a typo in a property name, everything lands in one group called 'undefined'. The key was turned into text.

Step 3: group by a number

Now group by age. Ada (34) comes first in the list, so you might expect the 34 group first.

Step 3

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];
const groupBy = (xs, keyOf) => xs.reduce((acc, x) => {
  (acc[keyOf(x)] ??= []).push(x);
  return acc;
}, {});
console.log(Object.keys(groupBy(staff, (s) => s.age))); // [ '29', '34' ]

Two surprises. The keys are strings, because every key of a plain object is a string. And they are in a different order: '29' comes first. Objects list keys that look like whole numbers in number order, before any other keys. The order you met them in is lost.

Step 4: group into a Map

A Map is a collection of key and value pairs whose keys can be any value, and it always keeps them in the order they were added.

Step 4

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];
const groupByMap = (xs, keyOf) => xs.reduce((acc, x) => {
  const key = keyOf(x);
  acc.set(key, [...(acc.get(key) ?? []), x]);
  return acc;
}, new Map());
const byAge = groupByMap(staff, (s) => s.age);
console.log([...byAge.keys()]);                   // [ 34, 29 ]
console.log(byAge.get(29).map((s) => s.name));    // [ 'Bola', 'Chi' ]

acc.get(key) ?? [] reads the bucket, or an empty list if there isn't one yet. Then set stores a new list with the person added. The keys stay numbers, and 34 stays first because it was seen first.

Step 5: the built-in Object.groupBy

Newer engines have this built in. It is recent, so test for it before relying on it.

Step 5

const staff = [
  { name: 'Ada', dept: 'ops' },
  { name: 'Bola', dept: 'eng' },
  { name: 'Chi', dept: 'ops' },
];
const hasGroupBy = typeof Object.groupBy === 'function';
console.log(hasGroupBy); // true
if (hasGroupBy) console.log(Object.groupBy(staff, (s) => s.dept).ops.map((s) => s.name)); // [ 'Ada', 'Chi' ]

hasGroupBy is true in node 26; an older browser may say false. Object.groupBy takes the list and a key function, just like yours, and gives the same groups. There is a Map.groupBy too, for when you want a Map.

The full solution

The panel has groupBy, groupByMap and the feature-tested Object.groupBy, and groups the staff by department and by age. Press Run and compare the two lines for age.

The answer

const staff = [
  { name: 'Ada', dept: 'ops', age: 34 },
  { name: 'Bola', dept: 'eng', age: 29 },
  { name: 'Chi', dept: 'ops', age: 29 },
  { name: 'Dami', dept: 'eng', age: 34 },
];

const groupBy = (xs, keyOf) => xs.reduce((acc, x) => {
  (acc[keyOf(x)] ??= []).push(x);               // create the bucket on first sight
  return acc;
}, {});

const groupByMap = (xs, keyOf) => xs.reduce((acc, x) => {
  const key = keyOf(x);
  acc.set(key, [...(acc.get(key) ?? []), x]);
  return acc;
}, new Map());

const names = (list) => list.map((s) => s.name);
const byDept = groupBy(staff, (s) => s.dept);
const byAge = groupByMap(staff, (s) => s.age);

// The built-in, where the engine has it.
const hasGroupBy = typeof Object.groupBy === 'function';
const builtIn = hasGroupBy ? Object.groupBy(staff, (s) => s.dept) : byDept;

console.log('groups     :', Object.keys(byDept), '<- insertion order');
console.log('ops        :', names(byDept.ops));
console.log('eng        :', names(byDept.eng));
console.log('by age, Map:', [...byAge.keys()], '<- still numbers');
console.log('by age, object keys:', Object.keys(groupBy(staff, (s) => s.age)), '<- strings, and reordered');
console.log('Object.groupBy available?', hasGroupBy);

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the groups are named after the key values', Object.keys(byDept), ['ops', 'eng']);
test('each group holds its members in input order', names(byDept.ops), ['Ada', 'Chi']);
test('and the groups account for everyone', byDept.ops.length + byDept.eng.length, staff.length);
test('an empty input produces no groups', groupBy([], (x) => x), {});
test('a Map accumulator keeps a numeric key numeric', [...byAge.keys()], [34, 29]);
test('while an object turns it into a string', Object.keys(groupBy(staff, (s) => s.age)), ['29', '34']);
test('and reorders it, because integer-like keys sort first', Object.keys(groupBy(staff, (s) => s.age))[0], '29');
test('a key function returning undefined groups under "undefined"', Object.keys(groupBy(staff, () => undefined)), ['undefined']);
test('Object.groupBy produces the same grouping where it exists', names(builtIn.ops), ['Ada', 'Chi']);

Also Basic 38. The angle here is the accumulator's type, and the assertions make the difference concrete: grouping by age into an object gives keys '29' and '34' in that order, even though 34 was seen first, because integer-like keys are enumerated numerically before the rest. Grouping into a Map keeps 34 and 29 as numbers and in the order encountered.

??= is what keeps the reduce to two lines: it assigns only when the left side is null or undefined, so the bucket is created once and appended to thereafter. Object.groupBy does all of this natively and is recent enough to be worth feature-testing, which is why the last assertion goes through a guard.

Common mistakes

  • Pushing into a bucket that doesn't exist yet. acc[key].push(x) throws the first time a key appears. Create the bucket first with ??= [].
  • Forgetting to return the accumulator. The next step then gets undefined.
  • Grouping by numbers into an object. The keys become strings and get reordered. Use a Map when type or order matters.

Try it yourself

  1. Group ['bus', 'keke', 'okada', 'car'] by word length.
  2. Group the staff by whether they are over 30, with keys 'over30' and 'under30'.
  3. Change groupBy so each bucket holds only names, not whole records.

Keep practising

Newsletter

New writing, when it lands.

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