admin管理员组文章数量:1387391
I tried using isNaN(value)
and !isNaN(value)
but I am unable to remove the NaN element in the give code without removing the strings. (Obviously because string is not a number).
function cleaner(arr) {
return = arr.filter(function f(value) {return (value !== false && value !== null && value !== 0 && value !== undefined)});
}
cleaner([7, "eight", false, null, 0, undefined, NaN, 9, ""]);
The above code should return [7, "eight", 9, ""];
I tried using isNaN(value)
and !isNaN(value)
but I am unable to remove the NaN element in the give code without removing the strings. (Obviously because string is not a number).
function cleaner(arr) {
return = arr.filter(function f(value) {return (value !== false && value !== null && value !== 0 && value !== undefined)});
}
cleaner([7, "eight", false, null, 0, undefined, NaN, 9, ""]);
The above code should return [7, "eight", 9, ""];
- P.s, I think I could have worded the title better but I'm not sure how. – salmanxk Commented Jan 28, 2016 at 3:16
-
false
andnull
andundefined
are notNaN
s. OnlyNaN
isNaN
– zerkms Commented Jan 28, 2016 at 3:16 - 1 Regardless, the last line of my post will explain what I actually want, to quell any confusion. – salmanxk Commented Jan 28, 2016 at 3:19
-
4
Guys, seriously, the question has nothing to do with
NaN
s. – zerkms Commented Jan 28, 2016 at 3:19 -
2
Just check if
typeof
of thevalue
is either astring
or anumber
and you're done. – zerkms Commented Jan 28, 2016 at 3:21
3 Answers
Reset to default 5This will return only numbers (without 0) and strings (including empty ones).
function cleaner(arr) {
return arr.filter(function(item){
return typeof item == "string" || (typeof item == "number" && item);
/** Any string**/ /** Numbers without NaN & 0 **/
});
}
console.log(cleaner([7, "eight", false, null, 0, undefined, NaN, 9, ""]));
//[7, "eight", 9, ""]
Using ES2015 Arrow Function syntax
array.filter(item => typeof item == "string" || (typeof item == "number" && item));
var filteredArr = [7, "eight", false, null, 0, undefined, NaN, 9, ""].filter(item => typeof item == "string" || (typeof item == "number" && !isNaN(item) && item));
console.log(filteredArr);
Some ways to detect whether x
is NaN
:
Number.isNaN(x)
(ES6)Object.is(x, NaN)
(ES6)x !== x
(typeof x === 'number') && isNaN(x)
Note: isNaN
alone is not a reliable way to check if a value is NaN
!
Since you want to filter out all falsy values except empty strings, all you need is
function cleaner(arr) {
return arr.filter(function(value) {
return value === '' || value;
});
}
If you had wanted to filter out all falsy values including empty strings, you could have done:
function cleaner(arr) {
return arr.filter(Boolean);
}
本文标签:
版权声明:本文标题:javascript - How can I use .filter() on an array to remove only 'NaN' but not strings and numbers? - Stack Overf 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744524353a2610654.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论