We use the filter
method to remove falsy values from an array. The filter
method filters out all the values that return false when passed to a function. When you use filter
and pass a Boolean constructor, you can quickly filter out all the falsy values from the array.
array.filter(function(currentValue, index, array), thisValue)
Parameter | Description |
(Required) | A function or search criteria to be used to filter values in the array. The function accepts three arguments:
|
(Optional) |
|
filter
returns a new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.
Note: There are only six falsy values in JavaScript:
undefined
,null
,NaN
,0
,""
, andfalse
.
const arr = [1, "test", undefined, null, 5, false, "", 3, NaN];const result = arr.filter(Boolean); // = > [1, "test", 5, 3]console.log(result);
filter
.arr.filter(Boolean)
filters all the falsy values present in the array and returns a new array.Free Resources