Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
prevstores 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
prevto 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.
