Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

배열을 취하고 모든 0을 JavaScript 끝으로 이동하는 알고리즘을 작성하십시오.

<시간/>

배열을 받아서 그 배열에 있는 모든 0을 추가 공간을 사용하지 않고 배열의 끝으로 이동하는 함수를 작성해야 합니다. 여기서는 Array.prototype.splice() 및 Array.prototype.push()와 함께 Array.prototype.forEach() 메서드를 사용합니다.

함수의 코드는 -

예시

const arr = [34, 6, 76, 0, 0, 343, 90, 0, 32, 0, 34, 21, 54];
const moveZero = (arr) => {
   for(ind = 0; ind < arr.length; ind++){
      const el = arr[ind];
      if(el === 0){
         arr.push(arr.splice(ind, 1)[0]);
         ind--;
      };
   }
};
moveZero(arr);
console.log(arr);

출력

콘솔의 출력은 다음과 같습니다. -

[34, 6, 76, 343, 90, 32, 34, 21, 54, 0, 0, 0, 0]