Group matching element in array in JavaScript

In JavaScript, grouping matching elements in an array is a common task that can be efficiently solved using the reduce() method. This approach allows us to iterate through an array and group consecutive duplicate elements together.

What is the reduce() Function?

The reduce() method is a built-in JavaScript function that processes each element of an array and accumulates a result. It takes a callback function with two main parameters: an accumulator (which stores the accumulated result) and the current value being processed.

Basic reduce() Example

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
}, 0);
console.log(sum);
15

Grouping Consecutive Elements

To group consecutive matching elements, we use reduce() to build an array of sub-arrays, where each sub-array contains identical consecutive elements.

Algorithm Steps

Step 1: Initialize an array with duplicate values

Step 2: Use reduce() to process each element

Step 3: Check if the current element matches the last processed element

Step 4: If different, create a new sub-array

Step 5: Add the current element to the appropriate sub-array

Step 6: Return the grouped result

Implementation Example

// Array with consecutive duplicate elements
const array = ['A','A','A','A','D','E','E','F','H','H','H','L','M','S','S','U','Y','Y'];

// Group consecutive matching elements
const groupedArray = array.reduce((accumulator, currentValue) => {
    // Check if this is a new group (different from last element)
    if (accumulator.last === undefined || accumulator.last !== currentValue) {
        accumulator.last = currentValue;
        accumulator.groups.push([]);
    }
    // Add current element to the last group
    accumulator.groups[accumulator.groups.length - 1].push(currentValue);
    return accumulator;
}, {groups: []}).groups;

console.log(groupedArray);
[
  [ 'A', 'A', 'A', 'A' ],
  [ 'D' ],
  [ 'E', 'E' ],
  [ 'F' ],
  [ 'H', 'H', 'H' ],
  [ 'L' ],
  [ 'M' ],
  [ 'S', 'S' ],
  [ 'U' ],
  [ 'Y', 'Y' ]
]

Alternative Approach - Simpler Implementation

const array = ['A','A','B','B','B','C','D','D'];

const groupedArray = array.reduce((result, current, index) => {
    // If first element or different from previous, start new group
    if (index === 0 || current !== array[index - 1]) {
        result.push([current]);
    } else {
        // Add to the last group
        result[result.length - 1].push(current);
    }
    return result;
}, []);

console.log(groupedArray);
[
  [ 'A', 'A' ],
  [ 'B', 'B', 'B' ],
  [ 'C' ],
  [ 'D', 'D' ]
]

Time and Space Complexity

Time Complexity: O(n) - We iterate through the array once, and each operation inside the reducer takes constant time.

Space Complexity: O(n) - We create a new array structure to store the grouped elements, which in the worst case (no duplicates) would be the same size as the input.

Key Points

  • This method only groups consecutive matching elements
  • Elements must be adjacent in the array to be grouped together
  • The reduce() method provides an elegant solution for array transformation tasks
  • The accumulator object tracks both the current groups and the last processed element

Conclusion

Grouping consecutive matching elements in JavaScript arrays is efficiently accomplished using the reduce() method. This approach provides O(n) time complexity and creates organized sub-arrays of identical consecutive elements, making it ideal for data processing and analysis tasks.

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

396 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements