Page 1 of 1

Not able to remove values in Array using the .splice() in Javascript

Posted: 2022-07-28, 14:13
by TimJohn909
I was trying to loop through an array and remove any values that equal false, null, 0, undefined, NaN, or "".

This is how it should work - When I call the function it should return a blank array but right now it's outputting [null,0,null,null,""]. Here's what I have so far.

Code: Select all

function bouncer(arr) {
      for(i=0;i<arr.length;i++){
        if(arr[i]===false||null||0||undefined||NaN||""){
          arr.splice(i,1);
        }
      }
    return arr;
    }

bouncer([false, null, 0, NaN, undefined, ""]);
What is wrong with the arr.splice() that I am making? I have used the .splice() exactly how it was mentioned here - https://www.scaler.com/topics/splice-in-javascript/ . But the elements are still there. Any pros here who can help?

Re: Not able to remove values in Array using the .splice() in Javascript

Posted: 2022-07-28, 15:04
by Moonchild
Your issue isn't with your usage of .splice() but rather 2 errors in your surrounding code:
  1. When removing elements from an array with splice(), remember that your array will re-index unless it's the last element. So you want to run backwards through the array to prevent skipping over elements as well as running over at the end of the array after removing an element.
  2. Your comparison in the "if" evaluates everything right of the === as the value to compare against, and that will likely type-coerce everything to a boolean. with making an exact type comparison (=== vs ==) you are additionally not catching anything but the "false". Of note, your comparison can simply be any "falsy" value so you can just do a !arr[ i ] check to catch anything that is false or 0 or null or "" or NaN or undefined.
You probably want:

Code: Select all

function bouncer(arr) {
      for(i=arr.length-1;i>=0;i--){ // -1 because it's 0-indexed!
        if(!arr[i]){
          arr.splice(i,1);
        }
      }
    return arr;
    }

bouncer([false, null, 0, NaN, undefined, ""]);
Unless I misunderstood what you're trying to do.