Notes

Edit on GitHub
JavaScript

.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Here is an animals array:

1const animals = [
2	{ name: "Fluffykins", species: "rabbit"},
3	{ name: "Caro", species: "dog"},
4	{ name: "Hamilton", species: "dog"},
5	{ name: "Harold", species: "fish"},
6	{ name: "Ursula", species: "cat"},
7	{ name: "Jimmy", species: "fish"}
8]

Here’s how you’d traditionally get all the dogs from the array:

1const dogs = []
2for (let i = 0; i < animals.length; i++) {
3	if (animals.species === 'dog') {
4		dogs.push(animals[i])
5	}
6}

Here’s how you’d do it using .filter():

1let dogs = animals.filter(function(animal) {
2	return animal.species === 'dog'
3})

.filter() will loop through every item in the array and pass it through the callback function. It expects the callback* function to send back a true or false, to tell .filter() whether or not the item should be in the new array. Then it’ll return the new filtered array.

You can write the same filter method by defining the callback function separately and then passing that to filter, like this:

1let isDog = function(animal) {
2	return animal.species === 'dog'
3}
4let dogs = animals.filter(isDog)