CKTIS / JavaScript
Map.groupBy: group iterable data into a Map
Map.groupBy iterates an iterable, computes a key for every element, and returns a Map whose values are arrays preserving input order.
Version: ECMAScript 2024 onward; example target: Node.js 24.22.2
Syntax
Map.groupBy(items, callbackFn)Map.groupBy(items, callbackFn) consumes elements from any iterable. For each one it calls callbackFn(value, index), with the index starting at 0, and appends the value to the array for the returned key. The result is a new ordinary Map; key order follows first occurrence, and values within every group retain iteration order.
Unlike Object.groupBy, a key can be any value, including an object without string conversion. Keys use SameValueZero: NaN groups with NaN, while -0 and +0 form one group represented by +0. Elements are neither copied nor cloned; group arrays hold the same values and object references as the input.
Non-iterable items, null/undefined, or a non-callable callback throws TypeError; a callback exception propagates and the active iterator is closed. The method has been standard since ECMAScript 2024. Choose it when keys must retain object identity; for safe string keys, Object.groupBy may be appropriate.
Examples
const engineering = { name: "Engineering" };
const support = { name: "Support" };
const people = [
{ name: "Ada", department: engineering },
{ name: "Lin", department: support },
{ name: "Grace", department: engineering },
];
const byDepartment = Map.groupBy(people, (person) => person.department);
for (const [department, members] of byDepartment) {
console.log(department.name, members.map(({ name }) => name).join(","));
}
console.log(byDepartment.get(engineering)[0] === people[0]);
const special = Map.groupBy([-0, 0, NaN, NaN], (value) => value);
console.log(special.size, special.get(0).length, special.get(NaN).length);
console.log(Object.is([...special.keys()][0], 0));Result
Engineering Ada,Grace Support Lin true 2 2 2 true