Group By Key With Map Output

Group array items by a computed key or property name into a Map that preserves first-seen key order and supports value projection.

JavascriptData Integrity

Code

javascriptsnippet
24 lines
export function groupBy(items, keyOf, valueOf = (item) => item) {
  if (!Array.isArray(items)) throw new TypeError("items must be an array");
  if (typeof keyOf !== "function") throw new TypeError("keyOf must be a function");
  if (typeof valueOf !== "function") throw new TypeError("valueOf must be a function");
  const groups = new Map();
  for (let index = 0; index < items.length; index += 1) {
    const item = items[index];
    const key = keyOf(item, index);
    let bucket = groups.get(key);
    if (!bucket) {
      bucket = [];
      groups.set(key, bucket);
    }
    bucket.push(valueOf(item, index));
  }
  return groups;
}

export function groupByProperty(items, property) {
  if (typeof property !== "string" || property.length === 0) {
    throw new TypeError("property must be a non-empty string");
  }
  return groupBy(items, (item) => (item == null ? undefined : item[property]));
}

How it works

Structurally, expect the functions groupBy and groupByProperty and nothing else.

Iteration happens inside for (let index = 0; index < items.length; index += 1) — everything outside it runs once. Failure is loud: TypeError aborts the current operation instead of degrading it.

What to watch for

  • The guard typeof keyOf !== "function" short-circuits the flow with an early throw when its condition holds.

Putting it to use

The entry-point signature is export function groupBy(items, keyOf, valueOf = (item)

The surface worth importing is groupBy; the helpers around it are private to the snippet.

Core lines

return groupBy(items, (item) => (item == null ? undefined : item[property]));
if (typeof valueOf !== "function") throw new TypeError("valueOf must be a function");
if (typeof keyOf !== "function") throw new TypeError("keyOf must be a function");

Interactive Tools for This Topic

FAQ

Does the code validate its input?
The code throws `TypeError` — the guard `typeof keyOf !== "function"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `groupBy`, `groupByProperty` at load time.