I found this cool way of using the Array.prototype.filter method to remove all non-numbers from a string, but am not entirely sure how it's using the Number prototype to achieve this:
var arr = '75number9';
arr.split(/[^\d]/).filter(Number); // returns [75, 9]
When I check typeof Number I get back 'function'. What is going on here?
Adding further to my confusion is that if I replace Number with String, the results are the same. It still works!
arr.split(/[^\d]/).filter(String); // returns [75, 9]
Array and Object as parameters, on the other hand, return this:
["75", "", "", "", "", "", "9"]
Very curious to understand this!
Number is a (constructor) function trying to return a number. Give it a literal number or a string which can be parsed to a number, and it returns that number. Give it something else, and it returns NaN.
Filter returns the values for which the callback function (in this case Number) returns a truthy value. Numbers which are != 0 and != NaN are truthy, and are thus returned.
As so, your example does not return 0 values:
var arr = '75number0';
arr.split(/[^\d]/).filter(Number);
// ["75"]
Notice that the values of the returned array are still strings. If we want them to be numbers, we can use map():
arr.split(/[^\d]/).filter(Number).map(Number);
// [75, 9]
In the case of using the String constructor instead of Number, it works because String is returning empty strings for the empty strings it is given, and empty strings ('') are falsy just like 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With