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
Selected Reading
Removing consecutive duplicates from strings in an array using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of strings. Our function should remove the duplicate characters that appear consecutively in the strings and return the new modified array of strings.
Example
Following is the code −
const arr = ["kelless", "keenness"];
const removeConsecutiveDuplicates = (arr = []) => {
const map = [];
const res = [];
arr.map(el => {
el.split('').reduce((acc, value, index, arr) => {
if (arr[index] !== arr[index+1]) {
map.push(arr[index]);
}
if (index === arr.length-1) {
res.push(map.join(''));
map.length = 0
}
}, 0);
});
return res;
}
console.log(removeConsecutiveDuplicates(arr));
Output
[ 'keles', 'kenes' ]
Simplified Approach
Here's a cleaner version using regular expressions and map method:
const arr = ["kelless", "keenness", "programming"];
const removeConsecutiveDuplicates = (arr) => {
return arr.map(str => str.replace(/(.)\1+/g, '$1'));
}
console.log(removeConsecutiveDuplicates(arr));
[ 'keles', 'kenes', 'programing' ]
How It Works
The regular expression /(.)\1+/g works as follows:
-
(.)- Captures any character in group 1 -
\1+- Matches one or more repetitions of the captured character -
g- Global flag to replace all occurrences -
'$1'- Replaces with the first captured group (single character)
Character-by-Character Approach
Alternative method using character comparison:
const removeConsecutiveDuplicates = (arr) => {
return arr.map(str => {
let result = '';
for (let i = 0; i < str.length; i++) {
if (str[i] !== str[i + 1]) {
result += str[i];
}
}
return result;
});
}
const testArray = ["bookkeeper", "mississippi", "hello"];
console.log(removeConsecutiveDuplicates(testArray));
[ 'bokeper', 'misisipi', 'helo' ]
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| Regular Expression | High | Good | All modern browsers |
| Character Loop | High | Very Good | All browsers |
| Original Reduce | Low | Good | ES6+ browsers |
Conclusion
Both the regex and character-by-character approaches provide cleaner solutions for removing consecutive duplicate characters. The regex method is more concise, while the loop method offers better performance for large strings.
Advertisements
