DEV Community

Telmo Goncalves
Telmo Goncalves

Posted on

filter() Array Method with Javascript

Recently I've found out about filtering array using type guards,
such as Number or Boolean and I thought it would be good to
write a small post about it.

I've posted a Tweet about this, which contain a really neat trick in my opinion:

Let's do this.


Type Guards

Take the following array example, where we'll have both falsy statements and strings:

const arr = [false, 'NextJS', undefined, 'React', null]
Enter fullscreen mode Exit fullscreen mode

My first approach here to filter the falsy statements and returns just the strings would be to go with something like the following:

const arr = [false, 'NextJS', undefined, 'React', null]

arr.filter(value => value && value) // ["NextJS", "React"]
Enter fullscreen mode Exit fullscreen mode

Which is perfectly fine, although there's a more elegant way of doing this:

const arr = [false, 'NextJS', undefined, 'React', null]

arr.filter(value => value && value)
arr.filter(Boolean) // ["NextJS", "React"]
Enter fullscreen mode Exit fullscreen mode

Both return exactly the same thing, aside from that I went ahead and tested the performance on both methods:

const arr = [false, 'NextJS', undefined, 'React', null]

// Took 0.030000024707987905 milliseconds to run
arr.filter(value => value && value)

// Took 0.004999979864805937 milliseconds to run
arr.filter(Boolean)
Enter fullscreen mode Exit fullscreen mode

It's amazing how faster it is to use .filter(Boolean).


What about numbers and string?

I liked this so much I went ahead and tried filtering numbers and strings, I ran a couple of examples, let's start with numbers:

const arr = [1, 2, 3, "4", 5, "6"]
Enter fullscreen mode Exit fullscreen mode

With this example we want to filter the numbers, removing all strings:

const arr = [1, 2, 3, "4", 5, "6"]

arr.filter(Number) // [1, 2, 3, "4", 5, "6"]
Enter fullscreen mode Exit fullscreen mode

This returns exactly the same array, "4" and "6" are being considered numbers, because well, they are numbers. Javascript is a tricky fellow.

If we actually had strings in our array it would work fine:

const arr = [1, 2, 3, "Fancy", 5, "Array"]

arr.filter(Number) // [1, 2, 3, 5]
Enter fullscreen mode Exit fullscreen mode

The only way I got to filter numbers, even when numbers are string ("4"), was by checking the data type:

const arr = [1, 2, 3, "4", 5, "6"]

arr.filter(value => typeof value === 'number' && value) // [1, 2, 3, 5]
Enter fullscreen mode Exit fullscreen mode

I thought it was a simple and short post that can probably help someone, and I hope it does. If there's anything else that you think I should write about or you need some help just let me know.

Follow me on Twitter

Top comments (0)