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

, 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++) {

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

so, if I pass a string, such as
,it doesn't work as I intend it to because the value of
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.


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];
for( var i = 1; i < iterable.length; i++) {
   if(iterable[i] != temp) {
       temp = iterable[i];

Hope it helps!