Reduce an array to groups in JavaScript

In JavaScript, you can group consecutive duplicate elements in an array using the reduce() method. This technique combines adjacent duplicate values while preserving the original order.

Problem Statement

Given an array with duplicate entries, we need to merge consecutive duplicate elements together:

const arr = ['blue', 'blue', 'green', 'blue', 'yellow', 'yellow', 'green'];
console.log("Input array:", arr);
Input array: [ 'blue', 'blue', 'green', 'blue', 'yellow', 'yellow', 'green' ]

The expected output should combine only consecutive duplicates:

[ 'blueblue', 'green', 'blue', 'yellowyellow', 'green' ]

Using Array.reduce() Method

The reduce() method is perfect for this task as it can accumulate values and track the previous element:

const arr = ['blue', 'blue', 'green', 'blue', 'yellow', 'yellow', 'green'];

const combineDuplicate = (arr = []) => {
    let prev = null;
    const groups = arr.reduce((acc, value) => {
        if (prev === value) {
            acc[acc.length - 1] += value;
        } else {
            prev = value;
            acc.push(value);
        }
        return acc;
    }, []);
    return groups;
};

console.log(combineDuplicate(arr));
[ 'blueblue', 'green', 'blue', 'yellowyellow', 'green' ]

How It Works

The function works by:

  • Tracking previous value: prev stores the last processed element
  • Comparing adjacent elements: If current value equals previous, concatenate to last group
  • Creating new groups: If different, start a new group in the accumulator
  • Updating tracker: Set prev to current value for next iteration

Alternative Implementation

Here's a more concise version without external variables:

const combineConsecutive = (arr) => {
    return arr.reduce((acc, current, index) => {
        if (index > 0 && arr[index - 1] === current) {
            acc[acc.length - 1] += current;
        } else {
            acc.push(current);
        }
        return acc;
    }, []);
};

const testArray = ['a', 'a', 'b', 'a', 'c', 'c', 'c'];
console.log(combineConsecutive(testArray));
[ 'aa', 'b', 'a', 'ccc' ]

Conclusion

The reduce() method provides an elegant solution for grouping consecutive duplicates in arrays. This approach preserves order and only combines adjacent identical elements, making it useful for data processing and string manipulation tasks.

Updated on: 2026-03-15T23:19:00+05:30

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements