0, 1 및 기타 숫자를 포함하는 숫자 배열이 있습니다. 우리는 이 배열을 받아 모든 1을 시작으로, 0을 끝으로 가져오는 JavaScript 함수를 작성해야 합니다.
이 함수의 코드를 작성해 봅시다 -
예
const arr = [3, 2, 1, 8, 9, 0, 1, 9, 0, 2, 1, 0, 2, 0, 1, 0, 1, 1, 4, 0,
3];
const segregate = arr => {
const copy = arr.slice();
for(let i = 0; i < copy.length; i++){
if(copy[i] === 0){
copy.push(copy.splice(i, 1)[0]);
}else if(copy[i] === 1){
copy.unshift(copy.splice(i, 1)[0]);
};
continue;
};
return copy;
};
console.log(segregate(arr)); 출력
콘솔의 출력은 -
[ 1, 1, 1, 3, 2, 8, 9, 1, 9, 2, 2, 1, 1, 4, 3, 0, 0, 0, 0, 0, 0 ]