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

snippet
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]));
}