Kovacs Akos Kovacs Akos - 5 months ago 16
Javascript Question

Move specified characters in an array

I get a list of elements given as parameter, this is input.

JSON.stringify(moveZeros([1,2,0,1,0,1,0,3,0,1]))


Script should move zeros to the end without changing other elements order.
My solution would looks like this code:

var moveZeros = function (arr) {
var args = Array.prototype.slice.call(arguments);

for(var i=0; i<args.length; i++) {
if (args[i] == 0)
args.splice(i);
args.push(0);
}

console.log(args);

return args;
}


This should append element's with zero value and append a new, 0 value to end of array. It only prints original array without modification.

Answer

It is because arguments is all the arguments passed in. You should be using arr and not arguments.

var moveZeros = function (arr) {
  var args = arr;
  ...
}

Also another issue you will face is when you loop from the start to the end and you move elements to the end, you will be skipping indexes as stuff slides down to fill in the hole that you just created. You should be using reduce() or loop from the end to the start if you are using a for loop.

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

console.log(JSON.stringify(moveZeros([1, 2, 0, 1, 0, 1, 0, 3, 0, 1])));