Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Object.groupBy: group iterable elements into an object

Object.groupBy iterates an iterable, calls a callback for every element, and returns a null-prototype object of group arrays.

Version: ECMAScript 2024 onward; example target: Node.js 24.22.2

Syntax

Object.groupBy(items, callbackFn)

Object.groupBy(items, callbackFn) obtains a synchronous iterator from items. For each element it calls the callback with the value and an increasing index starting at 0, then applies ToPropertyKey to the result. A key can therefore remain a string or Symbol; other results are converted to strings. Elements retain their input order within each group.

The result is a new null-prototype object, and each own property holds a new array for that group. Consequently "__proto__" is a safe ordinary key, but the result has no Object.prototype methods; use an operation such as Object.hasOwn to test keys. Choose Map.groupBy when arbitrary object keys, rather than property keys, must remain distinct.

The method has existed since ECMAScript 2024. null, undefined, a missing iterator, or a non-callable callback causes TypeError. Exceptions from iteration, the callback, or key conversion propagate, with iterator closing as required by the protocol. An index at or above 2**53 - 1 also causes TypeError; the method cannot finish an infinite iterable by itself.

Examples

const urgent = Symbol("urgent");
const tasks = [
  { name: "A", urgent: false },
  { name: "B", urgent: false },
  { name: "C", urgent: true },
  { name: "D", urgent: false }
];
const groups = Object.groupBy(tasks, (task, index) =>
  task.urgent ? urgent : (index % 2 === 0 ? "now" : "later")
);
console.log(Object.getPrototypeOf(groups) === null);
console.log(groups.now.map(task => task.name).join(","));
console.log(groups.later.map(task => task.name).join(","));
console.log(groups[urgent].map(task => task.name).join(","));

const safe = Object.groupBy(["x"], () => "__proto__");
console.log(Object.getPrototypeOf(safe) === null, safe.__proto__[0]);

Result

true
A
B,D
C
true x

The example groups by strings, index, and a Symbol, then shows the null prototype and safe __proto__ key.

Sources