filter
The filter() method returns a shallow copy of a portion of a given array that has been filtered down to only the elements of the given array that pass the test implemented by the provided function.
Syntax
// Using Arrow function
filter((element) => { /* … */ } )
filter((element, index) => { /* … */ } )
filter((element, index, array) => { /* … */ } )
// Using Callback function
filter(callbackFn)
filter(callbackFn, thisArg)
// Using Inline callback function
filter(function(element) { /* … */ })
filter(function(element, index) { /* … */ })
filter(function(element, index, array){ /* … */ })
filter(function(element, index, array) { /* … */ }, thisArg)
Parameters
The callback function is a predicate, it return the elements only when test condition satisfies true.
The callBack function have following arguments
element: The current element being processed.
index: The index of the current element being processed.
array: The array at which map is called upon.
thisArg: The value to be used as this when calling the callback function.
Examples
Using with array
let array = [2,15,12,48,46,23,55];
var result = array.filter((item) => (item % 2 !== 0));
console.log(result);
This example is to find the odd number from the array. By checking the condition item % 2 !== 0
, if the condition is true
current element is returned to the variable result
. If not it is not returned.
Using with object
var people = [{
id: 1,
name: "David",
age: 28
}, {
id: 2,
name: "Sara",
age: 35
}, {
id: 3,
name: "Jane",
age: 21
}, {
id: 3,
name: "Peter",
age: 55
}];
let young = people.filter(person => person.age < 35);
console.log(young);
The filter() method accepts a test function, and returns a new array young
containing only the elements of the original array
that pass the test condition person.age < 35
.