$ 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.
/** 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
uniqBycompares keys withSetsemantics (SameValueZero), so1and"1"are different butNaNequalsNaN.groupBykeys are coerced to strings in the fallback (trueand"true"collide). UseMap.groupByif you need non-string keys.Object.groupByreturns a null-prototype object —result.hasOwnPropertydoesn't exist; useObject.hasOwn(result, k).
Ad slot