0

I am trying to delete all the zeros in the array nums but for some reason the splice() method ignores one of the zeros. Can you tell me what the reason is?

var deleteZeroes = function(nums) {
  
    for(var i=0 ; i<nums.length ; i++)
        {
            if(nums[i]===0)
                {
                  nums.splice(i,1)
               
                }
        }
       
      return nums
};

deleteZeroes([0,0,4,0,3])
Zaid
  • 29
  • 6

2 Answers2

1

The task can be performed using the filter() method

Example: 1

var deleteZeroes = function(nums) {
    var n = nums.filter(x => x !== 0);
    return n
};

console.log(deleteZeroes([0,0,4,0,3]));

Example: 2 (Short syntax)

var deleteZeroes = (nums) => (nums.filter(x => x));

console.log(deleteZeroes([0,0,4,0,3]));
54ka
  • 3,501
  • 2
  • 9
  • 24
1

If you are not trying to create a new array and want to remove in the same array, an alternate way to make it work, is to iterate from the end in reverse, like

(var i=nums.length-1 ; i>=0 ; i--) { 
   //same code you have...
} 
RPDP
  • 1,713
  • 1
  • 11
  • 6