I\'m trying to filter all non-numeric elements out from an array. We can see the desired output when using typeof. But with Number, it filters zero out.
Here\'s the
The reason for this behavior is that 0, null, undefined, NaN is equivalent to false in JavaScript so, in the first case:
[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(Number);
when used Number as one of the params in the filter, it returns the number itself. So when 0 is passed it returns 0 which javascript understands as false. So, it returns
[-1, 1, 2, 3, 4]
So to be on the safe side it is advised to use Number.isFinite instead of just Number.
[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(Number.isFinite);
Gives same results as
[-1,0,1,2,3,4, Number(0), '','test'].filter(n=> typeof n === 'number');
would give.