Filtering an array of numbers, where 0 is a valid input

I am trying to filter a list of elements by their index, and it is possible that the first element is the element I want to get.

It seems like trying to filter 0 with

 arr.filter(function(f) { if (Number.isInteger(f)) return f; }); 

does not work. Although Number.isInteger(0) true.

Here is the fiddle I created to set an example. An array filter should have two values, not one.

https://jsfiddle.net/yb0nyek8/1/

+7
javascript filter
source share
3 answers

because 0 is false in returning javascript f, where f is 0, will essentially return false.

 arr.filter(Number.isInteger) 

should be all you need as the filter wants a function that returns true or false anyway.

+8
source share

The statement in your .filter() function returns 3 , 0 , undefined , which in the world of truth / falsity are true , false , false . This means that the return from the .filter() function is [3] .

If you want to return all integer values, use the following:

 var a1 = arr.filter(function(f) { return Number.isInteger(f); }); 

This will return [3,0] from the .filter() function.

+2
source share

Array.filter runs the given function for each element in the array and decides whether to save it or throw it based on whether the function returns true or false. No need to return the number yourself.

By returning the number, you end up returning the number 0, which array.filter treats as false, forcing it to not include it.

Since Number.isInteger () returns true or false on its own, just use it yourself.

 arr.filter(function (f){ Number.isInteger(f); }) 
+1
source share

All Articles