Algorithm/Codewars
[Codewars/JS] Moving Zeros To The End
hyebin Lee
2022. 1. 14. 15:40
Detail
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]
<code>
var moveZeros = function (arr) {
// 0 카운터 세기
let arrLength = arr.length;
let count = 0;
for (let i = 0; i <= arrLength + 1; i++) {
if (arr[i] === 0) {
count++;
}
}
// 0 제거하기
let newArray = arr.filter(function (item) {
return item !== 0;
});
// 카운터에 맞게 0 push
for (i = 0; i < count; i++) {
newArray.push(0);
}
console.log(newArray);
return newArray;
};
moveZeros([9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]);
<other code>
var moveZeros = function (arr) {
return arr.filter(function(x) {return x !== 0}).concat(arr.filter(function(x) {return x === 0;}));
}
var moveZeros = function (arr) {
var filtedList = arr.filter(function (num){return num !== 0;});
var zeroList = arr.filter(function (num){return num === 0;});
return filtedList.concat(zeroList);
}
filter함수로 0인 것과 0이 아닌것을 구분 후 concat()함수로 합쳤다.
이렇게 간단하게 풀 수 있다니 .. 다시 한번 놀랍다.
concat() 함수 ? 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.
var moveZeros = function (arr) {
return [...arr.filter(v => v !== 0), ...arr.filter(v => v === 0)]
}
이 방법은 애플코딩에서 배웠던 방법이라 다시보니 반가웠다!
이 방법을 자주 활용해서 내 코드가 점점 클린코드가 되면 좋겠다.. 🤔