DEV Community

Cover image for How to filter an array - JavaScript
SnowBit
SnowBit

Posted on

How to filter an array - JavaScript

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'
  },
]
Enter fullscreen mode Exit fullscreen mode

and now you want to filter for only green fruits,

const greenFruits = fruits.filter((fruits) => fruits.color === 'green')
Enter fullscreen mode Exit fullscreen mode

and the output will be,

[{
  color: "green",
  name: "Watermelon"
}, {
  color: "green",
  name: "Pear"
}]
Enter fullscreen mode Exit fullscreen mode

Discussion (0)