DEV Community

David Bell
David Bell

Posted on • Updated on • Originally published at davidbell.space

A Quick Look at the filter() Method in JavaScript

(╯°□°) .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

Top comments (0)