Updated:

✒ Reference: MDN Web Docs - Array.prototype.filter()

filter() function

filter() creates a new array with all elements that pass the test implemented by the provided function.

It returns a new array with the elements that passed the test. if no elements passed the test, then an empty array is returned.

// Arrow function
filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )

// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)

// Inline callback function
filter(function(element) { ... })
filter(function(element, index) { ... })
filter(function(element, index, array){ ... })
filter(function(element, index, array) { ... }, thisArg)
Parameters  
element Required. The current element being processed.
index Optional. The index of the current element being processed in the array.
array Optional. The array on which filter() was called.
thisArg Optional. Default value undefined. A value passed to the function to be used as its this value.

Examples

// Create an array with words longer than 6 letters.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

Leave a comment