JavaScript .filter() Method 💭

Mursal Furqan Kumbhar - Jul 4 '21 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player