JavaScript----- Moving Zeros To The End

Description:

Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.

console.log(moveZeros([false,10,0,1,2,0,1,3,"a"])); 
// returns[false,1,1,2,1,3,"a",0,0]

my answer:

function moveZeros(arr) {
  var j = 0;
  for (var i = 0; i < arr.length; i++) {
    if(arr[i] === 0) {
      arr.splice(i,1);   //找出0所在位置并用splice()方法删除0
      j += 1;
      i = i - 1;     //计算被删除的0的总个数
    }
  }
  for (var k = 0; k < j; k++){  //为数组添加被删除的0;
    arr.push(0);
  }
  return arr;
}

best answer,使用filter()方法

  • filter() 方法: 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
  • filter() 不会改变原始数组。
function moveZeros(arr) {
  return arr.filter(function(x) {return x !== 0}).concat(arr.filter(function(x) {return x === 0;}));
}
原文地址:https://www.cnblogs.com/kid2333/p/7506070.html