Stuck at Falsy Bouncer Code

Tell us what’s happening:
Describe your issue in detail here.
Falsy Bouncer: What is wrong in this code?

  **Your code so far**
function bouncer(arr) {
let neg = [false,null,0,"",undefined,NaN]
for(let i =0;i<arr.length;i++){
   if(neg.includes(arr[i])){
     console.log(arr[i],"value")
       arr.splice(i,1)
   }
}
console.log(arr)
return arr;
}

bouncer([null, NaN, 1, 2, undefined]);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36

Challenge: Falsy Bouncer

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncerFalsy Bouncer

Here, you modify the length of the array, which causes some elements to be skipped.
If you want to change the arr array in this way, you have to traverse its elements from end to beginning to avoid skipping elements.
for (let i = arr.length - 1; i >= 0; --i) {

no i want to skip some elements. i need to skip all falsy values from the array

I understand. When you use splice() method, it modifies the array length, and you will not check the next element that goes after the current.

Look at the example:

let arr = ['a', 'b', 'c', 'd'];

for (let i = 0; i < arr.length; ++i) {
  console.log(arr[i]) // this will output: a, b, d (no c here)
  if (arr[i] === 'b' || arr[i] === 'c')
    arr.splice(i, 1);
}

console.log(arr); // ['a', 'c', 'd']

sorry but I couldn’t understand properly. You are saying if I traverse the array from end to beginning then it will give me the correct output instead of beginning to end? I get this point that splice() method modifies the array length but it will modify in both the cases right?

am still figuring out how it is only printing a,b,d and skipping c :sweat_smile:

Yes. It will modify in both the cases, but if you go from the end, you won’t skip elements.
Look at what happens when you delete an element.
let arr = [‘a’, ‘b’, ‘c’, ‘d’]
you deleted ‘b’ at index 1 and your array now
[‘a’, ‘c’, ‘d’] and “i” is 1, so on the next iteration “i” would be 2, and you will check value at index 2 that is ‘d’.
‘c’ will be skipped because the elements have been shifted to the left

okay Got it. Thank you so much.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.