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
Compress array to group consecutive elements JavaScript
We are given a string that contains some repeating words separated by dash (-) like this:
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-monday-monday'; console.log(str);
monday-sunday-tuesday-tuesday-sunday-sunday-monday-monday-monday
Our job is to write a function that returns an array of objects, where each object contains two properties: val (the word) and count (their consecutive appearance count).
Expected Output Format
For the above string, the compressed array should look like this:
const arr = [{
val: 'monday',
count: 1
}, {
val: 'sunday',
count: 1
}, {
val: 'tuesday',
count: 2
}, {
val: 'sunday',
count: 2
}, {
val: 'monday',
count: 3
}]
This represents: monday appears once, then sunday once, tuesday twice consecutively, sunday twice consecutively, and finally monday three times consecutively.
How It Works
We split the string by dashes and use Array.prototype.reduce() to group consecutive elements:
- Split the string by '-' to get individual elements
- Use reduce to iterate through each element
- Check if the current element matches the last grouped element
- If yes, increment the count; if no, create a new group
Complete Implementation
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-monday-monday';
const str2 = 'friday-friday-sunday-tuesday-sunday-sunday-monday-thursday-monday';
const compressString = (str) => {
return str.split('-').reduce((acc, val) => {
const { length: l } = acc;
if (acc[l-1]?.val === val) {
acc[l-1].count++;
return acc;
} else {
return acc.concat({
val,
count: 1
});
}
}, []);
}
console.log("First string result:");
console.log(compressString(str));
console.log("\nSecond string result:");
console.log(compressString(str2));
First string result:
[
{ val: 'monday', count: 1 },
{ val: 'sunday', count: 1 },
{ val: 'tuesday', count: 2 },
{ val: 'sunday', count: 2 },
{ val: 'monday', count: 3 }
]
Second string result:
[
{ val: 'friday', count: 2 },
{ val: 'sunday', count: 1 },
{ val: 'tuesday', count: 1 },
{ val: 'sunday', count: 2 },
{ val: 'monday', count: 1 },
{ val: 'thursday', count: 1 },
{ val: 'monday', count: 1 }
]
Alternative Approach Using for Loop
const compressStringLoop = (str) => {
const elements = str.split('-');
const result = [];
for (let i = 0; i
Using for loop:
[
{ val: 'a', count: 2 },
{ val: 'b', count: 3 },
{ val: 'c', count: 1 },
{ val: 'a', count: 1 }
]
Key Points
- The function only groups consecutive elements, not all occurrences
- Uses optional chaining (
?.) to safely check the last element - The reduce approach is functional and concise
- Both approaches have O(n) time complexity
Conclusion
This array compression technique groups consecutive duplicate elements while preserving order. The reduce method provides an elegant functional approach, while the for loop offers a more readable alternative for complex logic.
