Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'Number' in Array.prototype.filter(Number) work?

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!

like image 350
i_made_that Avatar asked Apr 04 '14 22:04

i_made_that


1 Answers

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.

like image 108
Mikke Avatar answered Sep 20 '22 13:09

Mikke