Array.prototype.filter()
choi-0125
Posted on October 15, 2021
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']
Posted on October 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.