So today, we shall be discussing about .filter() method in JavaScript.
The Filter Method
The filter() method in JavaScript takes each element in an array and it applies a conditional statement against it. If this conditional statement returns true, the element gets pushed to the output array. Otherwise, the element does not get pushed to the output array.
The filter() method creates a new array with elements that fall under a given criteria from an existing array.
Syntax
var first_array = arr.filter(
function callback(element, index, array) {
// Returns true or false
}[, thisArg])
The syntax for filter is similar to that of map, except, the callback function should return true to keep the elements, or false otherwise. In the callback, only the element is required.
Example
In the below given example, odd numbers are "Filtered" out, leaving only even numbers.
const all_numbers = [1, 2, 3, 4];
const even_numbers = all_numbers.filter(number => number % 2 === 0);
console.log(even_numbers);
// [2, 4]
In the next example, filter() is used to get all the students whose grades are greater than or equal to 90.
const students = [
{ name: 'Mursal', grade: 96 },
{ name: 'Furqan', grade: 48 },
{ name: 'Ahmed', grade: 99 },
{ name: 'Anees', grade: 56 },
{ name: 'Burhan', grade: 90 }
];
const studentGrades = students.filter(
students => students.grade >= 90);
return studentGrades;
//[ { name: 'Mursal', grade: 96 },
// { name: 'Ahmed', grade: 99 },
// { name: 'Burhan', grade: 90 } ]
In our next article, we are going to discuss something even cooler.
Top comments (6)
Fun example: Because "classes" are functions,
.filter(Boolean).length
is magic for, for example, evaluating composed validation rules.Cool, but I've seen antipatterns like
It's always better to just do this:
My next planned article is on .map() π
The JavaScript Arrays are something that I "get" when explained to me, but I have a hard time really ingraining the concepts. So, it's very appreciated to see lots of examples like you provided-- thank you!
Thank you for This
Could you explain how to check multiple condition in filter method