Filter

Imagine you are trying to autocomplete a user's input as the user types in a form element. You have a list of possible inputs, and you want to suggest just the subset that contain what the user has typed so far.

Imagine you have a list of all anchor elements found in a page, and you want to winnow the list down to just those that link to unencrypted HTTP URLs.

Imagine you have split a mass of text into white-space separated tokens, and you want just those tokens that are numbers.

Each of these situations can be solved by writting code that follows this pattern:

keepers = []
for each item in items
if item meets criteria
add item to keepers

This pattern has been abstracted into the Array.filter method. The only piece that changes is the criteria used to evaluate an item. The criteria is a function that receives a single item as a parameter and reports back true or false. You pass this boolean predicate in as a parameter.

Using filter and arrow functions for your predicates, you solve all three of the problems above with very compact code:

// Find completions.
const suggestions = words.filter(word => word.contains(input));

// Find anchors with HTTP URLs.
const httpAnchors = as.filter(a => a.href.startsWith('http://'));

// Find numeric tokens.
const nums = tokens.filter(token => token.matches(/^\d+$/));

Try creating an array of numbers in your browser's console and filtering out just the positive numbers. Try creating an array of strings and filtering out just those that have more than three characters.

As with forEach, the element's index is passed as a second parameter to your predicate. If you want to retain only the even-indexed elements, you'd write:

const evens = items.filter((item, i) => i % 2 === 0);

Try creating an array and filtering all but the element at index 2.