Implement groupBy From Scratch in JavaScript
Implement groupBy from scratch in JavaScript with reduce and a null-prototype object, then match Object.groupBy and Map.groupBy from ES2024. Node.js 24.

groupBy takes a list and a function that names a group for each item, and returns the items collected under those names. It is one of the most useful helpers in everyday data work: orders by customer, files by extension, log lines by level. Lodash has had groupBy for years, and ES2024 added Object.groupBy and Map.groupBy to the language, available in Node.js 21 and later. The interview version asks you to write it yourself. The short answer is a reduce, and the follow-ups are about the object that holds the groups: a plain {} has inherited keys that can collide with group names, an object can only have string and symbol keys, and the order of the keys is not always the order you saw the groups in. This post builds groupBy on Node.js 24 with each of those in turn and compares it with the built-ins.
What groupBy does
const people = [
{ name: "Ana", city: "Hue" },
{ name: "Bo", city: "Hanoi" },
{ name: "Cy", city: "Hue" },
{ name: "Di", city: "Da Nang" },
];
console.log(Object.groupBy(people, (person) => person.city));[Object: null prototype] {
Hue: [ { name: 'Ana', city: 'Hue' }, { name: 'Cy', city: 'Hue' } ],
Hanoi: [ { name: 'Bo', city: 'Hanoi' } ],
'Da Nang': [ { name: 'Di', city: 'Da Nang' } ]
}The result maps each city to the people who live there, in the original order within each group. Notice the [Object: null prototype] marker: the built-in returns an object with no prototype, which is a detail we will reproduce and explain. The callback receives the item and its index, and its return value is converted to a property key.
The reduce answer
function groupBy(items, getKey) {
return items.reduce((groups, item, index) => {
const key = getKey(item, index);
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(item);
return groups;
}, {});
}
const byCity = groupBy(people, (person) => person.city);
console.log(Object.keys(byCity));
console.log(byCity.Hue.map((person) => person.name));[ 'Hue', 'Hanoi', 'Da Nang' ]
[ 'Ana', 'Cy' ]For each item, compute the key, create the group's array if it does not exist, and push the item. The accumulator is a fresh object created for this call, so changing it inside the reduce is safe: nothing outside can see it. The callback receives (item, index), as in the built-in.
This version has a bug that only appears with certain data, and it is the follow-up an interviewer is waiting for.
The inherited keys problem
A plain object {} inherits from Object.prototype, so some keys exist before you add anything. A group named constructor, toString or __proto__ finds something already there, the test !groups[key] is false, and the code pushes onto a value that is not an array.
for (const word of ["constructor", "__proto__", "toString"]) {
try {
groupBy([word], (item) => item);
} catch (error) {
console.log(word, error.name);
}
}constructor TypeError
__proto__ TypeError
toString TypeErrorEach lookup returns an inherited value: the Object function, the prototype object and a method. None of them has a push method, so the call throws. The same data would silently produce wrong groups in a version that used in or || instead of throwing. And __proto__ is also the root of prototype pollution bugs when group keys come from user input and code assigns to computed keys.
The fix is an accumulator with no prototype, and a lookup that does not rely on truthiness.
function groupBySafe(items, getKey) {
const groups = Object.create(null);
items.forEach((item, index) => {
const key = getKey(item, index);
if (!Object.hasOwn(groups, key)) {
groups[key] = [];
}
groups[key].push(item);
});
return groups;
}
const safe = groupBySafe(["constructor", "toString", "a", "constructor"], (word) => word);
console.log(safe);
console.log(Object.keys(safe));[Object: null prototype] {
constructor: [ 'constructor', 'constructor' ],
toString: [ 'toString' ],
a: [ 'a' ]
}
[ 'constructor', 'toString', 'a' ]Object.create(null) gives an object with no inherited keys, which is also what the built-in returns, and Object.hasOwn makes the existence check exact. With no prototype, even __proto__ is an ordinary key: assigning groups["__proto__"] = [] creates a normal own property.
The cost of a null-prototype object is that it lacks methods such as hasOwnProperty, toString and valueOf. Code that calls groups.hasOwnProperty("x") throws, so use Object.hasOwn(groups, "x") or "x" in groups. Printing with a template literal also fails with a TypeError, since there is no toString.
Keys are converted to strings
An object property key is a string or a symbol, and the key function's result is converted with the usual rules. Numbers become strings, and distinct values can collide.
const byParity = groupBySafe([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? "even" : "odd"));
const byNumberKey = groupBySafe([1.5, 1.2, 2.7, 2.1], (n) => Math.floor(n));
const collisions = groupBySafe([{ id: 1 }, { id: 2 }], (item) => item);
console.log(byParity);
console.log(Object.keys(byNumberKey));
console.log(Object.keys(collisions));[Object: null prototype] { odd: [ 1, 3, 5 ], even: [ 2, 4 ] }
[ '1', '2' ]
[ '[object Object]' ]The numeric keys come back as the strings '1' and '2'. The third case is the real hazard: two different objects used as keys both become the text [object Object], so they land in a single group. If you need to group by an object, a Map is the right result type, because a Map compares keys by identity and keeps them as they are.
Integer keys and ordering
Property order in objects follows a rule: integer-like keys come first in ascending order, then string keys in insertion order. So the order of groups is not always the order in which you saw them.
const byLength = groupBySafe(["bb", "a", "ccc", "dd"], (word) => word.length);
const mixed = groupBySafe(["x", "10", "2", "y"], (word) => word);
console.log(Object.keys(byLength));
console.log(Object.keys(mixed));[ '1', '2', '3' ]
[ '2', '10', 'x', 'y' ]The first group seen was length 2, yet 1 comes first in the keys. In mixed, the keys '2' and '10' are integer-like and sort numerically ahead of 'x' and 'y', in ascending order. If you need the groups in first-seen order, use a Map.
The Map version
Map.groupBy returns a Map and keeps keys of any type, with identity comparison, in the order they were first seen.
function mapGroupBy(items, getKey) {
const groups = new Map();
let index = 0;
for (const item of items) {
const key = getKey(item, index);
index += 1;
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(item);
}
return groups;
}
const first = { id: 1 };
const second = { id: 2 };
const grouped = mapGroupBy(
[first, second, first, { id: 1 }],
(item) => item,
);
console.log([...grouped.values()].map((group) => group.length));
console.log(grouped.has(first), grouped.size);
console.log(Map.groupBy(["bb", "a", "ccc", "dd"], (word) => word.length));[ 2, 1, 1 ]
true 3
Map(3) { 2 => [ 'bb', 'dd' ], 1 => [ 'a' ], 3 => [ 'ccc' ] }The input has first twice, second once and a separate object that looks like first. A Map keeps three groups, because keys are compared by identity, and the order follows first appearance. The built-in Map.groupBy shows the same behavior, with numeric keys staying numbers and the first group 2 in the order seen. The function takes any iterable, because it uses for...of, so it works on sets and generators, where an array method such as reduce would not.
Matching the built-in exactly
Object.groupBy(items, callback) uses the same callback signature, accepts any iterable, converts keys to property keys, returns a null-prototype object and puts the items in each group in iteration order. The function above is that, apart from the argument checks. The built-in throws a TypeError when the callback is not a function or the items are null or undefined.
function objectGroupBy(items, getKey) {
if (items == null) {
throw new TypeError("items must not be null or undefined");
}
if (typeof getKey !== "function") {
throw new TypeError("callback must be a function");
}
const groups = Object.create(null);
let index = 0;
for (const item of items) {
const key = getKey(item, index);
index += 1;
(groups[key] ??= []).push(item);
}
return groups;
}
console.log(objectGroupBy(new Set([1, 2, 3, 4]), (n) => (n % 2 ? "odd" : "even")));[Object: null prototype] { odd: [ 1, 3 ], even: [ 2, 4 ] }The assignment (groups[key] ??= []).push(item) creates the array when the key is missing and pushes in one expression. It works here because the object has no prototype, so a missing key reads as undefined. Do not use that shortcut on a plain {}, for the reasons above. Object.groupBy is in Node.js 21 and later and in current browsers, and Map.groupBy too, so check your targets before dropping a helper.
Variations
Counting per group is a common companion: group, then take the length of each. A direct count avoids storing the items.
const counts = Object.fromEntries(
Object.entries(Object.groupBy(people, (p) => p.city)).map(([city, group]) => [city, group.length]),
);
console.log(counts);{ Hue: 2, Hanoi: 1, 'Da Nang': 1 }Object.fromEntries returns a regular object, so the null-prototype marker disappears. For large inputs, a loop that increments a counter, without building the groups, uses far less memory.
Tests
import test from "node:test";
import assert from "node:assert/strict";
test("groupBySafe groups items and keeps their order", () => {
const result = groupBySafe([1, 2, 3, 4], (n) => (n % 2 ? "odd" : "even"));
assert.deepEqual(result.odd, [1, 3]);
assert.deepEqual(result.even, [2, 4]);
});
test("groupBySafe handles keys that exist on Object.prototype", () => {
const result = groupBySafe(["constructor", "toString"], (word) => word);
assert.deepEqual(Object.keys(result), ["constructor", "toString"]);
});
test("mapGroupBy keeps object keys apart", () => {
const a = {};
const b = {};
assert.equal(mapGroupBy([1, 2], (n) => (n === 1 ? a : b)).size, 2);
});ℹ tests 3
ℹ pass 3
ℹ fail 0How to present it
Write the reduce version first, since it is what the interviewer expects. Then say what is wrong with it. The inherited keys problem shows that you think about data you do not control, and the answer, a null-prototype object with Object.hasOwn, is short. Mention the integer-key ordering and string conversion as limits of an object result, and offer the Map as the answer to both. Close by saying that the language now has Object.groupBy and Map.groupBy, so in new code you would use them, with your own version only for older runtimes.


