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]);
To remove all null values from an object: Use the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array of keys. Check if each value is equal to null and delete the null values using the delete operator.
JavaScript Array filter() The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.
To remove all undefined values from an array: Use the Array. filter() method to iterate over the array. Check if each value is not equal to undefined and return the result. The filter() method will return a new array that doesn't contain any undefined values.
Summary. null is a special value in JavaScript that represents a missing object. The strict equality operator determines whether a variable is null: variable === null .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With