filter() Array Method with Javascript

January 9, 2020
views 3 min read

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]

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"]

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"]

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

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']

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"]

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]

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]

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.

Read next
Associative array
September 21, 2020