Skip to Content
UtilsArray

Array utils

import { groupBy, sortBy, chunk } from '@gg-software/utils';

groupBy, sortBy and uniqueBy take a key — either a property name or a selector function. All helpers return new arrays; inputs are never mutated.

groupBy

groupBy(users, 'role'); // { admin: [...], member: [...] } groupBy(orders, (o) => o.status); // { paid: [...], pending: [...] }

sortBy

Stable sort by one or more keys (earlier keys win).

sortBy(users, 'name'); sortBy(users, ['lastName', 'firstName']); sortBy(orders, (o) => o.total, 'desc');
ParameterTypeDefault
itemsT[]
bykey | selector | array of them
direction'asc' | 'desc''asc'

uniqueBy

Deduplicate by key; the first occurrence wins.

uniqueBy(users, 'email'); uniqueBy(points, (p) => `${p.x}:${p.y}`);

chunk

chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]

partition

Split by a predicate into [matching, rest].

const [active, inactive] = partition(users, (u) => u.active);

range

Numeric range, end exclusive.

range(4); // [0, 1, 2, 3] range(2, 5); // [2, 3, 4] range(0, 10, 5); // [0, 5]

sum / average

sum([1, 2, 3]); // 6 average([2, 4, 6]); // 4 average([]); // 0 (not NaN)

move

Move an item to another index — drag-and-drop reorder helper (pairs with ui’s KanbanBoard / sortable lists). Indices are clamped.

move(['a', 'b', 'c'], 0, 2); // ["b", "c", "a"]