.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:

const animals = [
	{ name: "Fluffykins", species: "rabbit"},
	{ name: "Caro", species: "dog"},
	{ name: "Hamilton", species: "dog"},
	{ name: "Harold", species: "fish"},
	{ name: "Ursula", species: "cat"},
	{ name: "Jimmy", species: "fish"}
]

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

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

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

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

.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:

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