JavaScript filter() method for beginners
(╯°□°)╯ .filter()
We use this function in JavaScript to return a new array from the items matched true from the condition passed in the function.
Example 1
const myArray = [1, 2, 3, 4];
const newArray = myArray.filter((num) => num >= 2);
// [ 2, 3, 4 ]
We used the filter function to filter through the numbers that matched true to the condition. In this case, the condition is to return numbers equal and bigger than 2 in a new array.
Example 2
We have an array of objects with criteria. We want to return a new array containing certain criteria from the array of objects.
const dogArr = [
{
name: "Spike",
age: 5,
vaccinated: true,
breed: "Border Terrior",
},
{
name: "Rex",
age: 8,
vaccinated: true,
breed: "Border Collier",
},
{
name: "Boeta",
age: 12,
vaccinated: false,
breed: "Labrador",
},
{
name: "Ozzy",
age: 2,
vaccinated: true,
breed: "German Shepard",
},
];
const isVaccinated = dogArr.filter((dog) => dog.vaccinated === true);
/* [
{name: "Spike", age:5, vaccinated:true},
{name: "Rex", age:8, vaccinated:true},
{name:"Ozzy", age:2, vaccinated:true}
]*/
In this example we wanted a new array of objects of the dogs that are vaccinated. We iterated through the data and returned the data that === true by using the filter() method.