Think you have a basket having some fruits in it, Watermelon, Mango, Pear, Peach. Now, you want to eat green fruits so you took Pear and watermelon. This is what we call filter and this same logic applies in filter()
method.
In javascript, we can filter array using a built-in filter()
method.
Let's go with the above example,
const fruits = [
{
name: 'Watermelon',
color: 'green'
},
{
name: 'Mango',
color: 'yellow'
},
{
name: 'Peach',
color: 'pink'
},
{
name: 'Pear',
color: 'green'
},
]
and now you want to filter for only green fruits,
const greenFruits = fruits.filter((fruits) => fruits.color === 'green')
and the output will be,
[{
color: "green",
name: "Watermelon"
}, {
color: "green",
name: "Pear"
}]
Top comments (0)