DEV Community

Cover image for JavaScript .filter() Method πŸ’­
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

JavaScript .filter() Method πŸ’­

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])
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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 } ]
Enter fullscreen mode Exit fullscreen mode

In our next article, we are going to discuss something even cooler.

Latest comments (6)

Collapse
 
commdao profile image
commdao

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!

Collapse
 
soql101 profile image
Gc

Could you explain how to check multiple condition in filter method

Collapse
 
matengodev profile image
Davis O Matengo

Thank you for This

Collapse
 
fjones profile image
FJones

Fun example: Because "classes" are functions, .filter(Boolean).length is magic for, for example, evaluating composed validation rules.

Collapse
 
mvoloskov profile image
Miloslav πŸ³οΈβ€πŸŒˆ πŸ¦‹ Voloskov

Cool, but I've seen antipatterns like

foo.map(x => check(x) ? bar(x) : null).filter(Boolean)
Enter fullscreen mode Exit fullscreen mode

It's always better to just do this:

foo.filter(check).map(bar)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mursalfk profile image
Mursal Furqan Kumbhar

My next planned article is on .map() 😊