DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Return Boolean or Element in .filter()?
Lost Semicolon πŸ’»πŸ–±
Lost Semicolon πŸ’»πŸ–±

Posted on • Updated on

Return Boolean or Element in .filter()?

I have been doing codewars in order to improve my JS skills. I am now at 7 kyu - graduated from 8 kyu -and I have been enjoying solving programming puzzles.

My recent challenge which caused me some bother concerned arrays. The task was as follows:

Given an arrays a and b, return values from array a which are not present in array b.

Seems simple at first sight. Essentially, we require a .filter() which will return an element. Such as:

function arrayDiff(a, b) {
  let newArray = a.filter(element => {
                      if(!b.includes(element)){
                        return element; 
                 }})
  return newArray;
}

However, when we run the test below, we are missing the 0 value.

Test.assertDeepEquals(arrayDiff([-20,16,6,3,-2,0],[-2,-20,16,3]), [6,0]) 
//output is [6]

It took me a while to figure out why this was happening.
In JavaScript, 0 can represent false and 1 can represent true.

By returning the value 0, we are indivertibly returning false, telling the .filter() function that there is no match and the element shouldn't be added to the new array.

Instead of returning the element, in this case, we should return a boolean.

And so the solution is:

function arrayDiff(a,b){
    return a.filter(element => !b.includes(element));
}

But when can I use element and not a boolean?

You should use "element" when you would like omit anything, which may be interpreted by JS as falsey. One of these examples could be removing undefined values from an array or empty strings.

Values which can be interpreted as falsy are:

  • false
  • null
  • undefined
  • 0
  • NaN
  • ''

Further reading:

CodeWars Cata
.filter() documentation
Helpful Stack Overflow question about it

Hope you enjoyed!

Top comments (0)

Layoffs: It’s Okay to Not Be Okay