(╯°□°)╯ .filter()
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 ]
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 } ] */
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)