JavaScript Array .filter() Method

The 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 true and false to discard an element.

The filter method:

  • 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

Signature

This method takes two parameters:

  • callback : the function that executes each of the elements of the array. The callback function is required and can take three parameters:

  • element: this is the element currently being executed - required.

  • index: the index of the current item - optional.

  • array: the array that is currently being processed - optional.

  • thisArg: an argument passed to be used as the this value in the callback - optional

// create a string
const names = ['John', 'Peter', 'James', 'Pammy'];

const myName = names.filter(name => name.includes('am'));
// output: Array ['James', 'Pammy']

Basic usage

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.