How to use array.filter() method in JavaScript
In es6, we got more useful methods in javascript, where one of them is filter()
method that
help us to filter the particular set of elements from the array.
Consider we have an array of numbers from 1 to 10, but we need only odd numbers from the array.
const numbers = [1,2,3,4,5,6,7,8,9,10];
We can use filter method to find the odd numbers.
const oddNumbers = numbers.filter((e, i) => e % 2 === 1);
console.log(oddNumbers);
// [1,3,5,7,9]
filter() method
The filter()
method creates a new array with the elements that passes the test condition (callback function).
syntax:
array.filter(function (element, index, array){
return condition;
})
It runs the callback function on the each element present in the array and keeps the elements whose return value is true or false to exclude it.
We can also use filter()
method to filter the array of objects.
const users = [
{id:1,name:"mas",present:true},
{id:2,name:"gowtham",present:false},
{id:3,name:"king",present:true},
{id:4,name:"major",present:false},
{id:5,name:"lol",present:false},
{id:6,name:"seth",present:true},
]
const presentUsers = users.filter((user) => user.present);
console.log(presentUsers);
Output:
[
{ id: 1, name: "mas", present: true },
{ id: 3, name: "king", present: true },
{ id: 6, name: "seth", present: true }
]