Emmanuel Akinfulubi

JavaScriptArray

Group consecutive equal values in JavaScript

Advanced · 4 min read

Grouping consecutive values means cutting a list wherever the value changes: [1, 1, 2, 2, 2, 3] becomes [[1, 1], [2, 2, 2], [3]]. You see this in chat apps that bunch several messages from the same person together, in timelines grouped by day, and in print dialogs that turn pages 1, 2, 3, 7, 8 and 10 into 1-3,7-8,10.

In this tutorial you will write groupConsecutive, then make the "do these belong together?" test something the caller can change. With that one change, the same function will also compress a list of page numbers. You should know arrays, arrow functions and reduce.

Neighbors only

This kind of grouping only ever looks at neighbors. A value joins the current group if it belongs with the value right before it. Otherwise it starts a new group. So [1, 2, 1] gives three groups, not two: the second 1 isn't next to the first.

That's different from grouping by key, which collects every matching value from anywhere in the list.

A test you can pass in

"Belongs with the value before it" usually means "is equal to it". But it doesn't have to. For page numbers, 2 belongs after 1 because it is exactly one more. If the function takes the test as an argument, both cases use the same code.

A default parameter lets you give that argument a value when the caller leaves it out:

JavaScript

const greet = (name = 'friend') => 'Hello, ' + name;
console.log(greet());      // Hello, friend
console.log(greet('Ada')); // Hello, Ada

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

47 Group consecutive values into runs

hard

Split [1, 1, 2, 2, 2, 3] into [[1, 1], [2, 2, 2], [3]]. Then make the "same group" test a parameter, and use it to compress [1, 2, 3, 7, 8, 10] into 1-3,7-8,10.

Stuck? Three hints, smallest first
  1. 1. Compare each value with the last value of the group in progress, not with the group as a whole.
  2. 2. Take the comparison as an argument, defaulting to (a, b) => a === b.
  3. 3. For number ranges the test is (a, b) => b === a + 1, and the input has to be sorted first.

Step 1: build the groups with reduce

reduce carries a list of groups along. For each value, look at the group in progress, groups.at(-1). If there is one and the value belongs, push it in. If not, start a new group holding just this value.

Step 1

const groupEqual = (xs) =>
  xs.reduce((groups, v) => {
    const current = groups.at(-1);
    if (current !== undefined && current.at(-1) === v) current.push(v);
    else groups.push([v]);
    return groups;
  }, []);

console.log(groupEqual([1, 1, 2, 2, 2, 3])); // [ [ 1, 1 ], [ 2, 2, 2 ], [ 3 ] ]
console.log(groupEqual([1, 2, 1]));          // [ [ 1 ], [ 2 ], [ 1 ] ]
console.log(groupEqual([]));                 // []

current.at(-1) is the last value in the group in progress, the neighbor of v. On the first value there is no group yet, so current is undefined, and the && stops before reading from it.

Remember to return groups at the end of the function. reduce uses whatever you return as the starting point for the next value.

Step 2: make the test a parameter

Swap current.at(-1) === v for a call to together, and give together a default that does the same comparison:

Step 2

function groupConsecutive(xs, together = (a, b) => a === b) {
  return xs.reduce((groups, v) => {
    const current = groups.at(-1);
    if (current !== undefined && together(current.at(-1), v)) current.push(v);
    else groups.push([v]);
    return groups;
  }, []);
}

const adjacent = (a, b) => b === a + 1;

console.log(groupConsecutive([1, 1, 2, 2, 2, 3]));         // [ [ 1, 1 ], [ 2, 2, 2 ], [ 3 ] ]
console.log(groupConsecutive([1, 2, 3, 7, 8, 10], adjacent)); // [ [ 1, 2, 3 ], [ 7, 8 ], [ 10 ] ]

adjacent says "b comes straight after a". 1, 2, 3 stay together, 7 breaks the group because it isn't 4, and so on.

Here is why the code compares with the group's last value. A tempting shortcut is to compare with the group's first value, current[0]. For equality the two are the same. For adjacent they aren't: when 3 arrives, the first value is 1, and 3 is not 1 + 1, so the group would wrongly break after 2.

Step 3: sort first

Because the function only sees neighbors, the order of the input decides everything:

Step 3

function groupConsecutive(xs, together = (a, b) => a === b) {
  return xs.reduce((groups, v) => {
    const current = groups.at(-1);
    if (current !== undefined && together(current.at(-1), v)) current.push(v);
    else groups.push([v]);
    return groups;
  }, []);
}
const adjacent = (a, b) => b === a + 1;

console.log(groupConsecutive([3, 1, 2], adjacent)); // [ [ 3 ], [ 1, 2 ] ]

That answer isn't wrong for this order, but it isn't what you wanted for a set of page numbers. Sorting them first is part of the job.

Step 4: compress page numbers

Three steps, in this order: remove duplicates, sort as numbers, then group. Each group then prints as one number, or as "first-last".

Step 4

function groupConsecutive(xs, together = (a, b) => a === b) {
  return xs.reduce((groups, v) => {
    const current = groups.at(-1);
    if (current !== undefined && together(current.at(-1), v)) current.push(v);
    else groups.push([v]);
    return groups;
  }, []);
}
const adjacent = (a, b) => b === a + 1;

const compressRanges = (nums) =>
  groupConsecutive([...new Set(nums)].sort((a, b) => a - b), adjacent)
    .map((run) => (run.length === 1 ? String(run[0]) : `${run[0]}-${run.at(-1)}`))
    .join(',');

console.log(compressRanges([3, 1, 2, 8, 7, 10])); // 1-3,7-8,10
console.log(compressRanges([5]));                 // 5

[...new Set(nums)] drops repeated numbers, because a Set keeps each value once. Without it, [1, 1, 2] would break at the second 1, since 1 is not 1 + 1. sort((a, b) => a - b) sorts as numbers, not as text. The backtick template string puts the first and last value of a run into text like '1-3'.

Step 5: group records by a field

The test can compare anything, including one field of an object:

Step 5

function groupConsecutive(xs, together = (a, b) => a === b) {
  return xs.reduce((groups, v) => {
    const current = groups.at(-1);
    if (current !== undefined && together(current.at(-1), v)) current.push(v);
    else groups.push([v]);
    return groups;
  }, []);
}

const shifts = [
  { name: 'Ada', dept: 'ops' },
  { name: 'Bola', dept: 'ops' },
  { name: 'Chi', dept: 'eng' },
];
const byDept = groupConsecutive(shifts, (a, b) => a.dept === b.dept);
console.log(byDept.map((g) => g.length)); // [ 2, 1 ]

Ada and Bola are both in ops and sit next to each other, so they share a group. Chi starts a new one.

The full solution

The panel has groupConsecutive, adjacent and compressRanges, and runs them on equal neighbors, page numbers, unsorted input and the shift records. Press Run and follow each line.

The answer

function groupConsecutive(xs, together = (a, b) => a === b) {
  return xs.reduce((groups, v) => {
    const current = groups.at(-1);
    if (current !== undefined && together(current.at(-1), v)) current.push(v);
    else groups.push([v]);
    return groups;
  }, []);
}

const adjacent = (a, b) => b === a + 1;

// Page ranges: sort, group the consecutive runs, then print each run.
const compressRanges = (nums) =>
  groupConsecutive([...new Set(nums)].sort((a, b) => a - b), adjacent)
    .map((run) => (run.length === 1 ? String(run[0]) : `${run[0]}-${run.at(-1)}`))
    .join(',');

const shifts = [
  { name: 'Ada', dept: 'ops' },
  { name: 'Bola', dept: 'ops' },
  { name: 'Chi', dept: 'eng' },
];

console.log('equal neighbours :', groupConsecutive([1, 1, 2, 2, 2, 3]));
console.log('a later repeat   :', groupConsecutive([1, 2, 1]), '<- three groups');
console.log('consecutive ints :', groupConsecutive([1, 2, 3, 7, 8, 10], adjacent));
console.log('compressed       :', compressRanges([3, 1, 2, 8, 7, 10]));
console.log('unsorted, ungrouped:', groupConsecutive([3, 1, 2], adjacent), '<- sort first');
console.log('by a field       :', groupConsecutive(shifts, (a, b) => a.dept === b.dept).map((g) => g.length));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('equal neighbours group together', groupConsecutive([1, 1, 2, 2, 2, 3]), [[1, 1], [2, 2, 2], [3]]);
test('a repeat that is not adjacent starts a new group', groupConsecutive([1, 2, 1]), [[1], [2], [1]]);
test('an empty list gives no groups', groupConsecutive([]), []);
test('the groups always partition the input', groupConsecutive([1, 1, 2]).flat(), [1, 1, 2]);
test('a custom test groups consecutive integers', groupConsecutive([1, 2, 3, 7, 8, 10], adjacent), [[1, 2, 3], [7, 8], [10]]);
test('which compresses a page list', compressRanges([3, 1, 2, 8, 7, 10]), '1-3,7-8,10');
test('a run of one prints as a single number', compressRanges([5]), '5');
test('unsorted input is not grouped, so sorting is part of the job', groupConsecutive([3, 1, 2], adjacent), [[3], [1, 2]]);
test('records group on whichever field you compare', groupConsecutive(shifts, (a, b) => a.dept === b.dept).map((g) => g.length), [2, 1]);

Comparing against current.at(-1) rather than against the group's first element is what makes the parameterised version work. For equality the two are the same; for "consecutive" they are not, since each value has to follow the one immediately before it.

The compression example is the practical use, and it needs three steps in the right order: de-duplicate, sort numerically, then group. Skip the sort and the assertion above shows what you get — [[3], [1, 2]], which is not wrong, merely an answer to a different question. That is the recurring hazard of run-based algorithms: they only see neighbours, so the ordering is your responsibility.

Common mistakes

  • Comparing with the group's first value. It works for equality but breaks for tests like adjacent. Compare with current.at(-1).
  • Forgetting to sort page numbers. The function only sees neighbors, so unsorted input gives scattered groups.
  • Forgetting return groups in the reducer. The next round then receives undefined and the code throws.

Try it yourself

  1. Group 'aabccc' into ['aa', 'b', 'ccc']. (Hint: spread the string, group, then join('') each group.)
  2. Group a list of temperatures into runs where each value is within 2 degrees of the one before.
  3. Write expandRanges('1-3,7-8,10') that gives back [1, 2, 3, 7, 8, 10].

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.