admin管理员组文章数量:1323335
I'm trying to remove all falsy values from an array.
I know this might not be the optimal solution for this problem but considering that I want to use the switch, is there a way to remove the NaN?
function bouncer(arr) {
arr=arr.filter(removeFalsy);
return arr;
}
function removeFalsy(val){
switch(val){
case false: return false;
case null: return false;
case 0: return false;
case "" :return false;
case undefined: return false;
case NaN: return false; // <=== NaN
default: return true;
}
}
bouncer([false, null, 0, NaN, undefined, ""]);
//result is: [ NaN ]
bouncer([1, null, NaN, 2, undefined]);
//result is: [ 1, NaN, 2 ]
I'm trying to remove all falsy values from an array.
I know this might not be the optimal solution for this problem but considering that I want to use the switch, is there a way to remove the NaN?
function bouncer(arr) {
arr=arr.filter(removeFalsy);
return arr;
}
function removeFalsy(val){
switch(val){
case false: return false;
case null: return false;
case 0: return false;
case "" :return false;
case undefined: return false;
case NaN: return false; // <=== NaN
default: return true;
}
}
bouncer([false, null, 0, NaN, undefined, ""]);
//result is: [ NaN ]
bouncer([1, null, NaN, 2, undefined]);
//result is: [ 1, NaN, 2 ]
Share
Improve this question
asked Aug 17, 2016 at 21:10
jruivojruivo
4971 gold badge8 silver badges23 bronze badges
3
-
NaN == NaN //false
Use Number.isNaN – VLAZ Commented Aug 17, 2016 at 21:12 -
Anyway, since
NaN
is a falsy value, you could just filter out, all falsy values – VLAZ Commented Aug 17, 2016 at 21:13 - Possible duplicates: Filter null from an array in JavaScript and How to filter() out NaN, null, 0, false in an array (JS). – Henke - Нава́льный П с м Commented Mar 17, 2021 at 10:37
3 Answers
Reset to default 7Sometimes you just need to keep it simple:
function bouncer(arr) {
return arr.filter(Boolean);
}
console.log(bouncer([false, null, 0, NaN, undefined, ""]));
console.log(bouncer([1, null, NaN, 2, undefined]));
NaN
is not equal to anything, therefore you need to use Number.isNaN.
As explained in the ments, the global isNaN is not a good idea.
Thanks for pointing that out.
For an example see how-do-you-have-a-nan-case-in-a-switch-statement
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Since false
, null
, 0
, ""
, undefined
and NaN
are all Falsy values in JavaScript therefore they will return false when tested.
function bouncer(arr) {
var array = arr.filter(function(val){
return val;
});
return array;
}
Only values which do not return false will be added to the array.
This question is same as this question.
本文标签: javascriptFiltering NaN from an arrayStack Overflow
版权声明:本文标题:javascript - Filtering NaN from an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742136602a2422397.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论