Basic Algorithm Scripting - Falsy Bouncer

Tell us what’s happening:
When I run my code, the bouncer function only seems to remove the empty string and not the ‘false’. Originally I thought the issue was with me using arrCopy.length since the length of arrCopy would change if an element is spliced out. I then tried to use arr.length in the for loop and ended up with the same output. I checked the hints and it says to use filter which I don’t have an issue with trying it out. I just don’t understand why the solution is tied to a functionality that isn’t taught until a later section of the course.
Your code so far

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

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

Your browser information:

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

Challenge: Basic Algorithm Scripting - Falsy Bouncer

Link to the challenge:

splice is dangerous.

function bouncer(arr) {
  const arrCopy = arr.slice();
  console.log("arrCopy:", arrCopy);
  for (let i = 0; i < arrCopy.length; i++) {
    if (arrCopy[i] == false){
      arrCopy.splice(i, 1);
    }
    console.log("i", i);
    console.log("arrCopy:", arrCopy);
  }
  return arrCopy;
}

Look at what happens when you splice out elements. Everything shifts, so i in the original array isn’t the locations in the copy anymore.

Try flipping your logic. Instead of looking for falsy elements to delete, why not only copy truthy elements from the original array in your loop?

1 Like

Thank you! I did just that and it worked. Rather than checking if (arrCopy[i] == false), I changed it to the inverse which is (arrCopy[i]). After that, I just pushed the elements that met the condition onto a new array and returned that.

1 Like

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