In JavaScript, I have an array containing boolean values and integer numbers, eg
[1, true, 2, false, 3]
I want to get an array with the boolean values removed. I tried
> [1, true, 2, false, 3].filter(Number)
[ 1, true, 2, 3 ]
Strangely, JavaScript thinks that false
is not a Number, but true is. How so?
If my array contains strings, it works.
> [1, '', 2, 'foo', 3].filter(Number)
[ 1, 2, 3 ]
I know I can write the following, I was hoping for an easier way.
> [1, true, 2, false, 3].filter(x => typeof x === 'number')
[ 1, 2, 3 ]
What’s the easiest way to achieve what I want?
Thanks
3
Answers
The
.filter()
method interprets the return value of the callback as boolean. If you useNumber()
as the filter callback, everything that evaluates to 0 orNaN
will be excluded from the result.What you really want to do is check the type of each value, which you can do with
typeof
.In case of just targeting integer or even safe integer values one could do …
… respectively …
… thats pretty much the easiest to go with.
And from another of my above comments …
Using the input provided in your question, try this:
[1, true, 2, false, 3].filter(el => (el === 0 || parseInt(el)));
Or try this simpler one
[1, true, 2, false, 3].filter(Number.isInteger);