I was asked to filter out NaN, null, 0, false in an array.
Luckily I have answered the question.
function bouncer(arr) {
function filterer(arr) {
return arr > 0|| isNaN(arr) === true;
}
arr = arr.filter(filterer);
return arr;
}
//example input
bouncer([0, 1, 2, 3, 'ate', '', false]); //output [1, 2, 3, 'ate']
but the thing is I really don't know how I came up with the answer or rather I don't know how it works. Specially on arr > 0 how did the filter know that arr is alread on arr[1], arr[2], etc.. without using a loop to iterate in all array.
or can simply just explain on how to code works. [I've tried to explain it clearly ---]
To remove all null values from an array:Use the Array. filter() method to iterate over the array. Check if each element is not equal to null . The filter() method returns a new array containing only the elements that satisfy the condition.
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function.
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.
If you were asked to filter out NaN
, null
, 0
, false
in an array, then your solutions doesn't really work.
Your input of:
bouncer([0, 1, 2, 3, 'ate', '', false, NaN]);
Will get the output of:
[1, 2, 3, 'ate', NaN]
To filter out all 'falsy' values you can simply use Boolean
:
function bouncer(arr) {
return arr.filter(Boolean);
}
bouncer([0, 1, 2, 3, 'ate', '', false, NaN]);
Output:
[1, 2, 3, 'ate']
Since the Boolean
constructor is also a function, it returns either true
for ‘truthy’ argument or false
for ‘falsy’ argument. If the value is omitted or is 0
, -0
, null
, false
, NaN
, undefined
, or the empty string (""
), the object has the value of false. All other values, including any object or the string "false"
, create an object with an initial value of true
.
You can also use an identity function instead of Boolean
.
function bouncer(arr) {
return arr.filter(x => x);
}
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