What is the typeof of 0?

3

I'm doing a function that extracts all the numbers from one array and stores them in another, but when I get to 0 it does not recognize it as a number, here my code:

function filter_list(l) {
  return l.filter(function(e){
     if(typeof e == "number") return e;
  });

}

Array passed as parameter: [1, 'a', 'b', 0,15] Array returned: [1,15], but it should be: [1, 0, 15]

Thanks and best regards.

    
asked by Juanma Perez 30.08.2018 в 13:51
source

1 answer

5

You are doing the filter wrong.

The filter function returns a boolean and depending on the returned value it takes or removes the element from the array. when you return a 0 it is equal to return false or null , as it is in the other cases where you do not return a value.

The correct use of the serial:

function filter_list(l) {
  return l.filter(function(e){
     return typeof e == "number";
  });
}

console.log(
  filter_list([1,'a','b',0,15])
);

Removing the clause if and returning the boolean directly.

    
answered by 30.08.2018 / 14:01
source