코테연습

35.Unique In Order

hxunz 2022. 4. 9. 09:02

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]

 


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

먼저, 결과를 담은 값들을 넣을 빈 배열을 만들어주었다.

let unique = [];

그 다음에는 for문을 사용해서 현재 요소가 다음 요소와 같지않다면(현재 알파벳이 다음 알파벳이랑 같지않다면)

현재 알파벳을 빈 배열에 넣어준다.

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