Ayush Bahuguna Ayush Bahuguna - 1 month ago 11
Javascript Question

Need to filter out repeating consecutive characters in a string using JavaScript

It is one of the challenges in Codewars, and I am supposed to write a function that will take a string and return an array, in which I can't have two consecutive identical elements. Also, the order should not change.

For example, if I pass a string

"hhhhheeeelllloooooohhheeeyyy"
, then the function should return an
array = ["h","e","l","o","h","e","y"]
.

This is my code.

var uniqueInOrder=function(iterable){
//your code here - remember iterable can be a string or an array
var unique = [];
for( var i = 0; i < iterable.length; i++) {
unique.push(iterable[i]);
}

for( var j = 0, k = 1; j < unique.length; j++, k = j + 1 ){
if(unique[j] === unique[k]){
unique.splice(k,1);
}
}
return unique;
}


so, if I pass a string, such as
"hhhhheeeeeellllloooo"
,it doesn't work as I intend it to because the value of
j
keeps incrementing, hence I can't filter out all the identical elements.

I tried tweaking the logic, such that whenever the
unique[j] === unique[k]
the value of j would become zero, and if that's not the case, then things would continue as they are supposed to do.

This got me an infinite loop.

I need your help.

Answer

The second for loop is fail because unique.length is not constant during the run. I think your problem can be solved like this:

var temp = iterable[0];
unique.push(iterable[0]);
for( var i = 1; i < iterable.length; i++) {
   if(iterable[i] != temp) {
       unique.push(iterable[i]);
       temp = iterable[i];
   }
} 

Hope it helps!

Comments