An object where keys represent group identifiers and values are arrays of grouped elements.
groupBy(
[{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "a" }],
(item) => item.type
);
// → { a: [{ id: 1, type: "a" }, { id: 3, type: "a" }], b: [{ id: 2, type: "b" }] }
groupBy([1, 2, null, 3], (n) => (n ?? "missing").toString());
// → { "1": [1], "2": [2], "missing": [null], "3": [3] }
Groups elements of an array by a key derived from each element.
The grouping key can be returned from a callback function. Handles
undefined
andnull
keys safely by grouping them under"__undefined__"
.