Reputation:
Well i have following type of input and desired output.What i basically want to do is remove consecutively repeating characters.(Keep first character removed all the following consecutively repeating).
input = dup(["abracadabra","allottee","assessee"])
output = ["abracadabra","alote","asese"].
input = dup(["kelless","keenness"])
output = ["keles","kenes"]
This is what i have done till now.
let arr1 = ["abracadabra", "allottee", "assessee"];
let arr2 = ["kelless", "keenness"];
function dup(input) {
return input.map(e => {
let tempOp = ''
for (let i = 0; i < e.length; i++) {
if (i === 0) tempOp += e[i];
else if (e[i - 1] !== e[i]) tempOp += e[i]
}
return tempOp;
})
}
console.log(dup(arr1))
console.log(dup(arr2))
I can do it with for loop. But is there any other better way of doing it. Can i do it with regex if yes any direction will help a lot.
Upvotes: 4
Views: 1960
Reputation: 5586
You can try the following Regex:
(.)\1+
and then replace the matches with $1
. That means:
Replace multiple occurrences with the match of first capturing group, which is
.
(matches any character only once).
let arr = [
'abracadabra',
'allottee',
'assessee',
'Gooooooooooooooogle',
'Vacuum'
];
arr = arr.map(val => val.replace(/(.)\1+/g, '$1'));
console.log(arr);
Upvotes: 7