最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Filter an array of numbers where 0 is a valid input - Stack Overflow

programmeradmin1浏览0评论

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.

/

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/yb0nyek8/1/

Share Improve this question edited Apr 24, 2016 at 8:28 Hamms 5,10723 silver badges29 bronze badges asked Apr 24, 2016 at 5:23 pedalpetepedalpete 21.6k45 gold badges133 silver badges245 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

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);
})
发布评论

评论列表(0)

  1. 暂无评论