JavaScript Understanding Array Filter Function with Examples for Beginners

Working with the array is a repetitive and boring task. Think of retrieving information provided by the user to search in the list and iterating every time. This process can be Simplified using the JavaScript Filter function has many real-world applications such as filtering through the list of items, retrieving specific information that matches to user input. In this post, we’ll learn about JavaScript Array Filter() function.

Table of Contents

Introduction

JavaScript Array Filter function used for filtering array items inside the list. It does not change existing array data but creates a new array that is filtered by a user-defined callback function. The callback function is called for every item of the array and if it matches to the condition specified by the user then it is returned.

Syntax

another_arr = arr.filter((item, index, array) => {
    //statements
}, other_args);

Array Filter Function Parameters/Arguments

  • Callback Function: This function can be anonymous or named function which is called for each item in an array arr. It takes the below parameters/arguments
    • item: Specifies current index item of an array.
    • index Specifies the current index of array item.
    • array (optional argument): Belongs to the whole array in this case its `arr`
  • other_args(optional) : This are some extra parameters that user can pass to function. You can retrieve these extra parameters using this the object inside the function.

Filter Even Numbers from an array

let numbers = [5,6,1,2,3,9,15];

let even_numbers = numbers.filter((item, index, array) => {
    if(item%2==0){
        return item;
    }
});

console.log("Even Numbers are : ",even_numbers);

//Console Output
Even NUmbers are :  (2) [6, 2]
Filter even numbers from array using JavaScript array.filter() method
Filter even numbers from an array using a JavaScript array.filter() method

Only arrays items which are even are returned using this returned items a new array even_numbers are created.

Simplify filter with arrow functions

We can simplify the above example with an arrow function which saves us a few lines of code.

let numbers = [4,5,6,1,2,3,9,15];

let even_numbers = numbers.filter((item, index, array) => (item%2==0));

console.log("Even Numbers are : ",even_numbers);

//Console Output
Even Numbers are :  (3) [4, 6, 2]
Using arrow function with filter method
Using the arrow function with the filter method

And the result is the same. It only returns array items that are even.

Use the function to filter even numbers

If you want to have a named function insisted of anonymous then you can go defined that function and pass it as an object to the array filter method as shown below.

let numbers = [4,5,6,1,2,3,9,15];

function getEvenNumbers(item,index){
    if(item%2==0){
        return item;
    }
}

let even_numbers = numbers.filter(getEvenNumbers);

console.log("Even Numbers are : ",even_numbers);

//Console Output
Even Numbers are :  (3) [4, 6, 2]
Use Callback function for filtering array
Use Callback function for filtering array

This is useful when you have a large number of code lines and you want to reuse functions in other parts of the program.

Filter students on basis of “Distinction”, “Passed”, “Failed”

Now we know the basics of the array filter function. It’s time to go for a real-life example. In the below example we’ll filter the list of students with their grades such as “Distinction”, “Passed”, “Failed”.

let students_info = [
    {name: "Kunal", percentage: 56.5},
    {name: "Ravi", percentage: 42},
    {name: "Nilesh", percentage: 75},
    {name: "Arjun", percentage: 32},
    {name: "Suma", percentage: 66},
    {name: "Rekha", percentage: 95},
    {name: "Abhinav", percentage: 29.5},
    {name: "Anirudh", percentage: 85},
    {name: "Suresh", percentage: 89},
    {name: "Ganesh", percentage: 22},
    {name: "Manish", percentage: 46},
];

function filter_students(item,index){
    let args = this;
    let grade = args["grade"];
    let data;
    switch(grade){
        case "FAILED" : 
            if(item["percentage"]<35){
                data = item;    
            }
            break;

        case "PASSED" : 
            if(item["percentage"]>=35 && item["percentage"]<85){
                data = item;    
            }
            break;

        case "DISTINCTION" : 
            if(item["percentage"]>=85 && item["percentage"]<=100){
                data = item;    
            }
            break;
    }

    return data;
}

let students_who_failed = students_info.filter(filter_students, {"grade" : "FAILED"});
let students_who_passed = students_info.filter(filter_students, {"grade" : "PASSED"});
let students_with_distinction = students_info.filter(filter_students, {"grade" : "DISTINCTION"});

console.log("All Students : ",students_info);
console.log("Failed Students : ",students_who_failed);
console.log("Passed Students : ",students_who_passed);
console.log("Students wih distinction : ",students_with_distinction);
Example for real-life use of array filter method to filter students based on the score
Example of real-life use of array filter method to filter students based on the score

Function filter_students takes two arguments they are item, index . item has each student object and index refers to that item index number.
As you can see that we have passed extra arguments as an object to a function that is grade. We can get grade an object inside function through this object which we have assigned to a variable args.
We’ll be filter students by their grade through switch statement and assign item to a variable data which is returned at bottom of the function.

Conclusion

We have come to the end of our post on JavaScript Understanding Array Filter Function with Examples for Beginners. If you like our content then please do share it and comment to clarify your doubts.

Related Posts

Summary
Review Date
Reviewed Item
JavaScript Understanding Array Filter Function with Examples for Beginners
Author Rating
51star1star1star1star1star
Software Name
Javascript Programming
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development