The filter()
method is a built-in method in JavaScript that allows you to create a new array with all elements that pass a certain test. This method takes a callback function as an argument, which defines the test that each element in the array must pass.
Here is an example of how you might use filter()
to create a new array:
// define an array of numbers
let numbers = [1, 2, 3, 4, 5, 6];
// create a new array with only even numbers
let evenNumbers = numbers.filter(function(number) {
return number % 2 == 0;
});
// log the new array to the console
console.log(evenNumbers); // [2, 4, 6]
In this example, we define an array of numbers called numbers
. We then use filter()
to create a new array called evenNumbers
, which contains only the even numbers from the original array. The filter()
method takes a callback function as an argument, which checks if the number
is even by checking if its remainder, when divided by 2, is equal to 0. If the number
is even, filter()
will include it in the new array.
You can also use filter()
to filter an array of objects based on a certain property. Here is an example of how you might do this:
// define an array of objects
let students = [
{ name: "John", grade: "A" },
{ name: "Jane", grade: "B" },
{ name: "Bob", grade: "A" }
];
// create a new array with only students who have an "A" grade
let topStudents = students.filter(function(student) {
return student.grade == "A";
});
// log the new array to the console
console.log(topStudents); // [{ name: "John", grade: "A" }, { name: "Bob", grade: "A" }]
In this example, we define an array of objects called students
, where each object represents a student with a name
and a grade
. We then use filter()
to create a new array called topStudents
, which contains only the students who have an "A" grade.
The filter()
takes a callback function as an argument, which checks if the student
has a grade
property with the value "A". If the student
has an "A" grade, filter()
will include it in the new array.