In a Codewars challenge, I have to create a function that takes a string and returns an array without consecutive identical elements while maintaining the original order.
For example, if the input is "hhhhheeeelllloooooohhheeeyyy"
, the function should output ["h","e","l","o","h","e","y"]
.
This is the code I came up with:
var uniqueInOrder=function(iterable){
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;
}
However, when I test it with a string like "hhhhheeeeeellllloooo"
, it fails because the value of j
keeps incrementing, preventing all identical elements from being filtered out.
I attempted modifying the logic so that if unique[j] === unique[k]
, the value of j
resets to zero. But this resulted in an infinite loop instead.
I'm struggling to fix this issue and would appreciate any help you can offer.