Falsy Bouncer Retaining the same array

Tell us what’s happening:
I know that the following code solves this challenge very effectively, however I was first experimenting another way and I wanted to discuss that way and get some feedback as I have not been able to make it work. Please see the second code snippet below for the code I am trying as well as the debugging code I wrote to wrap my mind around what’s happening.

Solution that works

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  var truthy = [];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i]) {
      truthy.push(arr[i]);
    }
  }
  return truthy;
}

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

What I tried -

function bouncer(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (!arr[i]) {
      arr.splice(i, 1);
    } 
  }
  return arr;
}

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

I figure out the above was not working due to the index being changed everytime I splice and hence the values of i skips elements. Figure this out by doing below -

function bouncer(arr) {
  var boolCollect = [];
  for (var i = 0; i < arr.length; i++) {
    console.log("inspecting: ", arr[i]);
    if (!arr[i]) {
      boolCollect.push(true);
    } else { boolCollect.push(false); }
  }
  console.log(boolCollect);
  return arr;
}

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

My question is, instead of filtering out the truthy values and making a new array as I am doing in the solution in the very first code snippet, is there a way to eliminate the falsy values from the same array and return. I have been going through the array methods documentation and haven’t been able to put it together yet.

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/falsy-bouncer

From my understanding filter does not change the existing array but creates a new array with the elements that pass the filter test. Which is essentially a shorter way of doing what I have already done. My aim was to avoid having any new arrays whatsoever and mutating the original.

But you can do someArray = someArray.filter(filterFunction).

1 Like

needed a flick on forehead for missing the obvious there, can be solved in one line instead of the looping and conditioning.

function bouncer(arr) {
  arr = arr.filter(element => element);
  return arr;
}

Thanks-You @ArielLeslie!

1 Like

You are right! Accuracy with the language is important and what I was going for was not creating additional unnecessary variables. I understand what you mean when you say even in this case a new array is created and referenced to the same arr variable.