Unique In Order

Lee·2022년 7월 8일

Algorithm

목록 보기
41/92
post-thumbnail

❓ Unique In Order

Q. 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

//#my solution
function uniqueInOrder(it) {
  let result = [];
  let last;

  for (let i = 0; i < it.length; i++) {
    if (it[i] !== last) {
      result.push((last = it[i]));
    }
  }

  return result;
}


//#other solution
var uniqueInOrder=function(iterable){
    return [...iterable].filter((a, i) => a !== iterable[i-1])
}
profile
Lee

0개의 댓글