$ snippet array-group-unique-chunk

Group, unique and chunk an array

The three lodash helpers people install a whole library for — groupBy, uniqBy and chunk — in a few lines each.

JavaScript
/** Group items by a key function. Uses Object.groupBy where available. */
function groupBy(arr, keyFn) {
  if (typeof Object.groupBy === "function") return Object.groupBy(arr, keyFn);
  return arr.reduce((acc, item) => {
    const k = keyFn(item);
    (acc[k] ||= []).push(item);
    return acc;
  }, {});
}

/** Unique by a key function (or by value if none). Keeps first occurrence. */
function uniqBy(arr, keyFn = (x) => x) {
  const seen = new Set();
  return arr.filter((item) => {
    const k = keyFn(item);
    if (seen.has(k)) return false;
    seen.add(k);
    return true;
  });
}

/** Split into chunks of `size`. */
function chunk(arr, size) {
  if (size < 1) throw new RangeError("size must be >= 1");
  const out = [];
  for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
  return out;
}

How it works

Plain arrays of primitives can be deduplicated with [...new Set(arr)]; the helper above extends that to objects by letting you pick the key. Object.groupBy is standard in modern engines and the reduce fallback covers the rest. All three are O(n) and don't mutate the input.

Gotchas

Try it
Result
Ad slot