Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  106] [ 1]  / answers: 1 / hits: 101368  / 8 Years ago, tue, december 27, 2016, 12:00:00

I have a task to remove false, null, 0, "", undefined, and NaN elements from an given array. I worked on a solution which removes all except null. Anyone can explain why? Here's the code:


function bouncer(arr) {
var notAllowed = ["",false,null,0,undefined,NaN];
for (i = 0; i < arr.length; i++){
for (j=0; j<notAllowed.length;j++) {
arr = arr.filter(function(val) {
return val !== notAllowed[j];
});
}
}
return arr;
}

bouncer([1,"", null, NaN, 2, undefined,4,5,6]);

More From » arrays

 Answers
37

Well, since all of your values are falsy, just do a !! (cast to boolean) check:


[1,"", null, NaN, 2, undefined,4,5,6].filter(x => !!x); //returns [1, 2, 4, 5, 6]

Edit: Apparently the cast isn't needed:




document.write([1,, null, NaN, 2, undefined,4,5,6].filter(x => x));




And the code above removes "", null, undefined and NaN just fine.


[#59554] Friday, December 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamila

Total Points: 490
Total Questions: 94
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;