Filtering values

Download javascript eBook

Example

The filter() method creates an array filled with all array elements that pass a test provided as a function.

5.1
[1, 2, 3, 4, 5].filter(function(value, index, arr) {
  return value > 2;
});
6
[1, 2, 3, 4, 5].filter(value => value > 2);

Results in a new array:

[3, 4, 5]

Filter falsy values

5.1
var 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:

  1. Boolean(0) returns false
  2. Boolean(undefined) returns false
  3. Boolean({}) returns true which means push it to the returned array
  4. Boolean(null) returns false
  5. Boolean('') returns false
  6. Boolean(true) returns true which means push it to the returned array
  7. Boolean(5) returns true which means push it to the returned array

so the overall process will result

[ {}, true, 5 ]

Another simple example

This example utilises the same concept of passing a function that takes one argument

5.1
function startsWithLetterA(str) {
    if(str && str[0].toLowerCase() == 'a') {
        return true
    }
    return false;
}

var str              = 'Since Boolean is a native javascript function/constructor that takes [one optional paramater] 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';
var strArray         = str.split(" ");
var wordsStartsWithA = strArray.filter(startsWithLetterA);
//["a", "and", "also", "a", "and", "array", "as"]

Stats

Contributors: 8
2017-02-17
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook