Array.prototype.filter()

choi0125

choi-0125

Posted on October 15, 2021

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
💖 💪 🙅 🚩
choi0125
choi-0125

Posted on October 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

10 example of filter using in js
javascript 10 example of filter using in js

February 6, 2024

Array.prototype.filter()
javascript Array.prototype.filter()

October 15, 2021