DEV Community

choi-0125
choi-0125

Posted on

Array.prototype.filter()

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 provided callbackFn 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 the callbackFn test are skipped, and are not included in the new array.
-MDN

Syntax

Arrow Function

filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )
Enter fullscreen mode Exit fullscreen mode

Inline Callback Function

filter(function callbackFn(element) { ... })
filter(function callbackFn(element, index) { ... })
filter(function callbackFn(element, index, array){ ... })
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
lioness100 profile image
Lioness100

In example 2, Strings#length isn't a function, it's a property