Search code examples
for-loopsplice

incremental/ decremental for-loops for removing elements from an array using splice


I'm trying to remove falsy elements from an array. When I run an incremental for loop like the one shown here, it only removes one falsy value at index 2 and not the one at index 3, yet when I run a decremental for loop, like the one shown below, it removes both (all) falsy values from the array. Why? It would seem to me that i should iterate through the array either way. What am I missing?

function bouncer(arr) {
    for(var i=0;i<arr.length;i++){
        if(Boolean(arr[i]) === false){
           arr.splice(i,1);
        }
  }
console.log(arr);
}

bouncer([7, "ate", "", false, 9]);

function bouncer(arr) {
    for(var i=arr.length-1;i>=0;i--){
        if(Boolean(arr[i]) === false){
           arr.splice(i,1);
        }
  }
console.log(arr);
}

bouncer([7, "ate", "", false, 9]);

Solution

  • Since your removing the element with Splice your skipping to the element ahead. Try subtracting the variable by 1 everytime you remove an element.

     function bouncer(arr) {
        for(var i=0;i<arr.length;i++){
            if(Boolean(arr[i]) === false){
               arr.splice(i,1);
               i--;
            }
      }
    console.log(arr);
    }
    
    bouncer([7, "ate", "", false, 9]);