I'm solving this problem where
Given an array of numbers, I need to move all zeros at the end of the array (in-place without making a copy of an array)
For example: given nums = [0, 1, 0, 3, 12]
After calling your function, nums should be [1, 3, 12, 0, 0].
My attempt:
var moveZeroes = function(nums) {
var count=0;
//Remove anything that's not Zero.
nums.forEach(function(val, index){
if(val==0){
nums.splice(index, 1);
count++;
}
});
//Fill in Zeros at the end
for(var i=0; i< count ; i++){
nums.push(0);
}
};
var input1 = [0,1,0,3,12];
var input2 = [0,0,1];
moveZeroes(input1)
console.log(input1); //Works!
moveZeroes(input2)
console.log(input2); //fails!
Issue:
It works with inputs like [0,1,0,3,12] but it fails in input such as [0,0,1] (The output I get is 0,1,0); Why? How can I fix it?
splicing) from an array that you are currently looping through