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]
function moveZeros(arr) {
let array = arr.filter((num) => num !== 0);
for (i=0; i < arr.length; i++) {
if (arr[i] === 0) {
array.push(0)
}
}
return array;
}
우선 주어진 숫자로 되어있는 배열에서 0을 제거해주었다. filter()
let array = arr.filter((num) => num !== 0);
그 다음에는 주어진 배열에서 처음 요소부터 반복하면서 요소가 0인 경우에는 array 배열 맨 뒤에 0을 추가해주었다. push()
for (i=0; i < arr.length; i++) {
if (arr[i] === 0) {
array.push(0)
}
}
'코테연습' 카테고리의 다른 글
40. 신규 아이디 추천 (0) | 2022.05.05 |
---|---|
39.Valid Parentheses (0) | 2022.04.28 |
37.Simple Pig Latin (0) | 2022.04.11 |
36.Does my number look big in this? (0) | 2022.04.10 |
35.Unique In Order (0) | 2022.04.09 |
댓글