moveZeros.js

Codewars 알고리즘 풀이


Problem

  • Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
    • 다른 element의 순서를 유지하면서 모든 0을 끝으로 이동시킨다.



Solution 01

function moveZeros(arr) {
  let arr1 = [];
  let arr2 = [];
  
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 0) {
      arr2.push(arr[i]);
    } else {
      arr1.push(arr[i]);
    }
  }
  return arr1.concat(arr2);
}

moveZeros([0, 1, 2]);          // [1, 2, 0]
moveZeros([0, 0, 1, 2]);       // [1, 2, 0, 0]
moveZeros(['a', 0, true, 4]);  // ['a', true, 4, 0]
moveZeros([1, null, 0, 4]);    // [1, null, 4, 0]


Solution 02

function moveZeros(arr) {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] === 0) {
      arr.splice(i, 1);
      arr.push(0);
    }
  }
  return arr;
}

moveZeros([0, 1, 2]);          // [1, 2, 0]
moveZeros([0, 0, 1, 2]);       // [1, 2, 0, 0]
moveZeros(['a', 0, true, 4]);  // ['a', true, 4, 0]
moveZeros([1, null, 0, 4]);    // [1, null, 4, 0]


Solution 03

function moveZeros(arr) {
  let arr1 = arr.filter(i => i !== 0);
  let arr2 = arr.filter(i => i === 0);
  
  return arr1.concat(arr2);
}

moveZeros([0, 1, 2]);          // [1, 2, 0]
moveZeros([0, 0, 1, 2]);       // [1, 2, 0, 0]
moveZeros(['a', 0, true, 4]);  // ['a', true, 4, 0]
moveZeros([1, null, 0, 4]);    // [1, null, 4, 0]


Solution 04

function moveZeros(arr) {
  return arr.filter(i => i !== 0).concat(arr.filter(i => i === 0));
}

moveZeros([0, 1, 2]);          // [1, 2, 0]
moveZeros([0, 0, 1, 2]);       // [1, 2, 0, 0]
moveZeros(['a', 0, true, 4]);  // ['a', true, 4, 0]
moveZeros([1, null, 0, 4]);    // [1, null, 4, 0]