Falsy values not getting spliced

I wrote a function to splice individual values of an array which would get converted into false using Boolean, but not all values are getting spliced

function bouncer(array) {
  for(let i=0;i<array.length;i++){
	  if(Boolean(array[i])===false){
		  array.splice(i,1);
	  }
  }
  return array;
}

console.log(bouncer([7, "ate", "", false, 9]));
console.log(bouncer([false, null, 0, NaN, undefined, ""]));

Output of the following code :

~/JSADSC-FCC/BasicAlgo$ node falsyBouncer
[ 7, 'ate', false, 9 ]
[ null, NaN, '' ]

In the first passed array, false should’ve also been spliced, but it did not. Same is the case of null, NaN & ‘’ in second passed array

You have two problems. One is a bug and one is a style problem.

  1. Removing elements as you iterate over the array changes the length of the array and position of the elements. Your loop can’t work correctly like this.

  2. The challenge intends you to use the concept of ‘falsy’, so instead of Boolean(array[i]) === false, try using array[i] as your condition.

2 Likes