filter() method returns an array containing elements of the parent array that match the set test. A function containing a test is passed as an argument to the
filter method. To keep an element the test function should return
false to discard an element.
- Will take a test function
- Returns a new array containing the elements that matches the set test
- Returns an empty array if there are no matches
This method takes two parameters:
callback: the function that executes each of the elements of the array. The callback function is
requiredand can take three parameters:
element: this is the element currently being executed -
index: the index of the current item -
array: the array that is currently being processed -
thisArg: an argument passed to be used as the
thisvalue in the
// create a string const names = ['John', 'Peter', 'James', 'Pammy']; const myName = names.filter(name => name.includes('am')); // output: Array ['James', 'Pammy']
Processing an array of numbers and returning the numbers that are within a set range. e.g: Checking if a person is old enough to watch the Deadpool movie.
Filtering a list of objects using their similar properties. E.g Getting the students that passed a set.
Getting elements within an array that exist over an index.