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
로 맨 뒤로 옮기고,i
를1
줄여서 같은index
를 다시 검사하게 함.
배열 전체 길이에서0
의 개수만큼만 반복문을 돌린 결과 값을return
.