Skip to content

Latest commit

 

History

History
36 lines (26 loc) · 983 Bytes

unique-in-order.md

File metadata and controls

36 lines (26 loc) · 983 Bytes

Unique In Order 6 Kyu

LINK TO THE KATA - ALGORITHMS FUNDAMENTALS

Description

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]

Solution

const uniqueInOrder = iterable => {
  const result = []

  for (let i = 0; i < iterable.length; i++) {
    const currentCharacter = iterable[i]
    const previousCharacter = iterable[i - 1]

    if (currentCharacter !== previousCharacter) result.push(currentCharacter)
  }

  return result
}