The Array.prototype.filter()
method in JavaScript allows you to create a new array with only the elements that pass a certain test. The filter()
method takes a callback function as an argument, which should return a Boolean value indicating whether or not the element should be included in the new array.
One use case for the filter()
method is to remove falsy values from an array. You can do this by using the Boolean function as the callback for the filter()
method. The Boolean
function returns true
for values that are "truthy" and false
for values that are "falsy". In JavaScript, the following values are considered falsy:
false
0
(zero)''
(empty string)null
undefined
NaN
(Not a Number)
Here is an example of how to use the filter(Boolean)
trick to remove falsy values from an array:
const values = [0, 1, '', 'hello', null, undefined, false, true, NaN];
const truthyValues = values.filter(Boolean);
console.log(truthyValues); // [1, 'hello', true]
In this example, the filter()
method is called on the values array and passed the Boolean
function as the callback. The filter()
method will then iterate through each element in the values
array and include any elements for which the Boolean
function returns true
in the new truthyValues
array.
Here is another example of using the filter(Boolean)
trick to remove falsy values from an array of objects:
const users = [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Bill', age: 35 },
{ id: 4, name: 'Mary', age: 40 },
{ id: 5, name: '', age: null }
];
const validUsers = users.filter(user => Boolean(user.name) && Boolean(user.age));
console.log(validUsers);
/*
[
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Bill', age: 35 },
{ id: 4, name: 'Mary', age: 40 }
]
*/
In this example, the filter()
method is used to remove any users who have an empty string for their name
or a null
value for their age
. The filter()
method is passed a callback function that uses the Boolean
function to check if the name
and age
properties of each user are truthy. The filter()
method will then include only the users for which the callback function returns true
in the new validUsers
array.
The filter(Boolean)
trick is a useful technique for removing falsy values from an array in JavaScript. It can be a powerful way to filter and transform data to meet your specific needs.
I hope you will find this trick helpful and will help you in your journey. Feel free to give me suggestions.
Take care developer ๐