Member-only story
Find and filter are a couple of the common array methods used and there are slight differences between the two.
The “find” method returns the first item that it finds.
The “filter” method returns all the items that meet the requirement.
Below we will use this example of an array of objects called “pups”.
const pups = [
{
"name": "Mr. Bonkers",
"isGoodDog": false
},
{
"name": "Nugget",
"isGoodDog": false
},
{
"name": "Skittles",
"isGoodDog": false
},
{
"name": "Buttercup",
"isGoodDog": false
},
{
"name": "Lucipher",
"isGoodDog": true
},
{
"name": "Snooper Pooper",
"isGoodDog": false
},
{
"name": "Puddles",
"isGoodDog": true
},
{
"name": "Mittens",
"isGoodDog": true
},
{
"name": "Middens",
"isGoodDog": true
},
{
"name": "Fido",
"isGoodDog": true
}
]
Example using the “find” method:
const findGoodDog = pups.find((pup) => {
return pup.isGoodDog === true
})// => returns { "name": "Lucipher", "isGoodDog": true }
Using the the “filter” method:
const filterGoodDog = pups.filter((pup) => {
return pup.isGoodDog === true
})// => returns { "name": "Lucipher", "isGoodDog": true }, {"name": "Puddles","isGoodDog": true },{"name": "Mittens","isGoodDog": true},{"name": "Middens","isGoodDog": true},{"name": "Fido","isGoodDog": true}