I'm trying to filter a list of elements by their index, and it is possible that the first item is the item I want to get.
It seems that trying to filter a 0
using
arr.filter(function(f) {
if (Number.isInteger(f)) return f;
});
does not work. Though Number.isInteger(0)
is true.
Here's a fiddle I've created to show an example. The array filtered should have two values, not one.
https://jsfiddle.net/yb0nyek8/1/
because 0 is a falsey value in javascript returning f where f is 0 will essentially be returning false.
arr.filter(Number.isInteger)
should be all you need since filter wants a function that returns true or false anyways.
The statement within your .filter()
function is returning 3
, 0
, undefined
, which in the truthy/falsey universe is true
, false
, false
. This means 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.
Array.filter runs a given function on each item in the array, and decides whether to keep it or toss it based on whether the function returns true or false. There's no need to return the number on your own.
By returning the number itself, you end up returning the number 0, which array.filter perceives as "false", causing it to not include it.
Since Number.isInteger() returns a true or false on its own, just use it by itself.
arr.filter(function (f){
Number.isInteger(f);
})
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