DEV Community

loading...

A Quick Look at the filter() Method in JavaScript

davidbell_space profile image David Bell Originally published at davidbell.space Updated on ・1 min read
(╯°□°) .filter()
Enter fullscreen mode Exit fullscreen mode

The filter() function in JavaScript returns a new array containing items that match true from the condition passed in the function.

const myArr = [1, 2, 3, 4, 5, 6]

const over2 = myArr.filter(el => el > 2)
// [ 3, 4, 5, 6 ]
Enter fullscreen mode Exit fullscreen mode

We used filter() to return the elements that are > 2. Filter returns a new array with all the elements that match the condition true.

Let's have another look.

Let's say we have an array of objects and we want a new array that match a certain criteria.

const goodBoys = [
  { name: "spike", trained: true },
  { name: "winston", trained: false },
  { name: "scruffy", trained: true },
]
const isTrained = goodBoys.filter(el => el.trained === true)

/* [ { name: 'spike', trained: true },
  { name: 'scruffy', trained: true } ] */
Enter fullscreen mode Exit fullscreen mode

In the example we wanted a new array of objects containing all the dogs that are trained. Using filter() we iterated the elements and return the trained elements === true

Let's connect

Connect on Twitter - davidbell_space

Discussion

pic
Editor guide