Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an array of numbers where 0 is a valid input

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/

like image 452
pedalpete Avatar asked Apr 24 '16 05:04

pedalpete


3 Answers

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.

like image 90
karina Avatar answered Oct 06 '22 09:10

karina


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.

like image 43
Brett DeWoody Avatar answered Oct 06 '22 10:10

Brett DeWoody


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);
})
like image 1
Euroclydon37 Avatar answered Oct 06 '22 10:10

Euroclydon37