Skip to main content

groupWith()

groupWith<T>(array, predicate): T[][]

Groups adjacent elements that satisfy a predicate function.


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the array.


Parametersโ€‹

array: readonly T[]โ€‹

The input array to group.

predicate: (a, b) => booleanโ€‹

A function that returns true if two adjacent elements should be grouped.


Returns: T[][]โ€‹

An array of arrays, where each inner array contains consecutive elements that satisfy the predicate.


Sinceโ€‹

2.0.0


Performanceโ€‹

O(n) time & space, single pass with early returns for empty/single-element arrays.


Also known asโ€‹

chop (Effect) ยท groupWith (Ramda) ยท โŒ (Lodash, es-toolkit, Remeda, Radashi, Modern Dash, Antfu)


Exampleโ€‹

groupWith([0, 1, 2, 4, 5], (a, b) => a + 1 === b);
// => [[0, 1, 2], [4, 5]]

groupWith(['a', 'a', 'b', 'c', 'c'], (a, b) => a === b);
// => [['a', 'a'], ['b'], ['c', 'c']]

groupWith([20, 21, 22, 15, 16], (a, b) => Math.abs(a - b) <= 2);
// => [[20, 21, 22], [15, 16]]

How it works?โ€‹

Groups consecutive elements using a comparator function. Creates new group when comparator returns false.

Step-by-stepโ€‹


Use Casesโ€‹

Group consecutive numbers ๐Ÿ“Œโ€‹

Cluster adjacent elements that form a sequence. Perfect for detecting runs, segmenting ranges, or identifying gaps in data.

const numbers = [1, 2, 3, 10, 11, 12, 20, 21];

const consecutiveRuns = groupWith(numbers, (a, b) => b - a === 1);
// => [[1, 2, 3], [10, 11, 12], [20, 21]]

Group words by first letterโ€‹

Segment sorted text data when the first character changes. Perfect for building alphabetical indexes or organizing sorted lists.

const words = ["apple", "apricot", "banana", "blueberry", "cherry"];

const byFirstLetter = groupWith(words, (a, b) => a[0] === b[0]);
// => [["apple", "apricot"], ["banana", "blueberry"], ["cherry"]]

Group transactions by consecutive typeโ€‹

Cluster adjacent items sharing the same attribute value. Useful for detecting patterns, batching operations, or summarizing streaks.

const transactions = [
{ id: 1, type: "credit" },
{ id: 2, type: "credit" },
{ id: 3, type: "debit" },
{ id: 4, type: "debit" },
{ id: 5, type: "credit" },
];

const byType = groupWith(transactions, (a, b) => a.type === b.type);
// => [[credit, credit], [debit, debit], [credit]]