Solving Codewars kata problem "Unique In Order"

codewars kata with iterables in JavaScript

Solving Codewars kata problem "Unique In Order"

This will be a relatively short article written to solve the codewars problem 'Unique In Order' where we are expected to write a function that performs a check on the arguments provided and if they are letters i.e. A-Z, the function should arrange them in the order they appear and in the case the arguments appear multiple times, the function should disregard the extra letters.

Here's is the problem.

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

For example:

uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3])       == [1,2,3]

we will first create an instance of an array.

var arr = [];

We then use a for loop to iterate through the arguments of the function (iterable as seen in the code below), and within that loop we will add an if loop to check if there are any repeating characters. If there is, we will ignore the subsequent equal and like characters and if there isn't we will push the current character to the already declared array arr.

for (var i=0;i<iterable.length;i++) {
if (iterable[i] !== iterable[i+1]) {
        //do nothing if the same
        // if not, push the current value to arr
      arr.push(iterable[i]);
    }
  }
  return arr;

Let's put the whole code together and try it out.

var uniqueInOrder = function (iterable) {
var arr = [];

for(var i = 0; i < iterable.length;i++ ){
//check if there is a repeating letter

if(iterable[i] !== iterable[i+1]){
 //push the remaining value to arr 
arr.push(iterable[i]);

         }

     }
return arr;
}

This solution :

  • should work with empty array.

  • should work with one element.

  • should reduce duplicates.

  • should treat lowercase as different from uppercase.

  • and work with integer and character arrays.