Filtering values
suggest changeThe filter() method creates an array filled with all array elements that pass a test provided as a function.
[1, 2, 3, 4, 5].filter(function(value, index, arr) {
return value > 2;
});
[1, 2, 3, 4, 5].filter(value => value > 2);
Results in a new array:
[3, 4, 5]
Filter falsy values
const filtered = [ 0, undefined, {}, null, '', true, 5].filter(Boolean);
Since Boolean is a native javascript function/constructor that takes [one optional parameter] and the filter method also takes a function and passes it the current array item as parameter, you could read it like the following:
Boolean(0)returns falseBoolean(undefined)returns falseBoolean({})returns true which means push it to the returned arrayBoolean(null)returns falseBoolean('')returns falseBoolean(true)returns true which means push it to the returned arrayBoolean(5)returns true which means push it to the returned array
The result is [ {}, true, 5 ]. 0n is also falsy, so Boolean removes it too.
Another simple example
This example utilises the same concept of passing a function that takes one argument
function startsWithLetterA(str) {
if(str && str[0].toLowerCase() == 'a') {
return true
}
return false;
}
const str = 'Since Boolean is a native javascript function/constructor that takes [one optional parameter] and the filter method also takes a function and passes it the current array item as a parameter, you could read it like the following';
const strArray = str.split(" ");
const wordsStartsWithA = strArray.filter(startsWithLetterA);
// ["a", "and", "also", "a", "and", "array", "as", "a"]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents