20% discount for your first project

Get a Quote

Array.filter()

Array.filter()

Suboor Khan

#Javascript
Array.prototype.filter()

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function. The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method. Syntax:



JavaScript Demo: Array.filter()


     
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"]


    
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. callbackFn is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callbackFn test are skipped, and are not included in the new array.

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


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


// Inline callback function
filter(function callbackFn(element) { ... })
filter(function callbackFn(element, index) { ... })
filter(function callbackFn(element, index, array){ ... })
filter(function callbackFn(element, index, array) { ... }, thisArg)
    
HomeServicesCase StudiesHire Us