CodeWars 코딩 문제 2021/01/15 - Moving Zeros To The End

이호현·2021년 1월 15일
0

Algorithm

목록 보기
52/138

[문제]

Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.

moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]

(요약) 배열 요소에서 0만 뒤쪽으로 다 옮겨라.

[풀이]

var moveZeros = function (arr) {
  const zeroCount = arr.filter(el => el === 0).length;

  for(let i = 0; i < arr.length - zeroCount; i++) {
    if(arr[i] === 0) {
      arr.push(arr.splice(i, 1)[0]);
      i--;
    }
  }

  return arr;
}

배열에서 0의 개수를 구함.
반복문을 돌면서 splice()0을 빼서 push로 맨 뒤로 옮기고, i1 줄여서 같은 index를 다시 검사하게 함.
배열 전체 길이에서 0의 개수만큼만 반복문을 돌린 결과 값을 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글