What is filter?
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
-MDN
How does filter work?
filter()
calls a providedcallbackFn
function once for each element in an array, and constructs a new array of all the values for which callbackFn returns a value that coerces to true... Array elements which do not pass thecallbackFn
test are skipped, and are not included in the new array.
-MDN
Syntax
Arrow Function
filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )
Inline Callback Function
filter(function callbackFn(element) { ... })
filter(function callbackFn(element, index) { ... })
filter(function callbackFn(element, index, array){ ... })
callbackFn
:
this is a function evaluate the element
passed in. It returns true
or false
for the element
depending if they meet or do not meet the condition, respectively.
it accepts 3 arguments:
-
element
: The current element being processed in the array. -
index
(optional): The index of the current element being processed in the array. -
array
(optional):The array filter was called upon.
Examples
Example 1.
const names = ['judy', 'joey', 'devon', 'charlie', 'sanjay']
let jNames = names.filter(name => name.indexOf('j') >= 0)
console.log(jNames);
//expected output: ['Judy,'Joey','Sanjay']
Example 2.
const vegis = ['tomato', 'garlic', 'green onion', 'asparagus', 'avocado']
let shortVegi = vegi.filter(vegetable => vegi.length() < 7)
console.log(shortVegetables)
//expected output: ['tomato', 'garlic']
Top comments (1)
In example 2,
Strings#length
isn't a function, it's a property