NaN / recursion issue

For this challenge we are given an array as input, and need to return an array which is identical to the initial array, except with none of the falsy values. After some testing, the round-about function below works for every (tested) array that does not contain NaN, but it fails as soon as NaN is added to a (any arbitrary) test array. Yes, it’s easier overall to just filter the initial array via the built-in Boolean function, which returns the desired result, but this seems like “magic” to me. Could someone explain to me why the round-about recursive function below gets hung up on NaN? I’m sure I would learn something deep and interesting about how NaN works (and what makes it different from other falsy values).

function bouncer(arr) {
     if (arr.map(arg => Boolean(arg)).indexOf(false) == -1){
            return arr;
     } else {
     return bouncer(
           arr.filter(
                 item => item != arr[arr.map(arg => Boolean(arg)).indexOf(false)]
                 )
           )
     }
}

Code explanation:

Base condition: given an array (source), we map it into an array of T/F values (representation of source), with each falsy value in the source array represented by an F in the representation array; when there is no F in the representation array, we return the source array.

Recursion: In the N+1th case, we call the main function (bouncer) on the result of filtering an Nth source array through a “checker” function, which ensures that the first item in the Nth source corresponding to an F in the representation is filtered out.

This is hard to describe in English. Anyway, the base case is reached after every falsy value has been filtered out of the source array, and it is the result of the final filtration which is returned. Why/how does NaN disrupt this process?

  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0.

Challenge: Falsy Bouncer

Link to the challenge:

I think that you have not considered that NaN === NaN is false, and NaN == false is false


I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

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