Gice

Technology and General Blog

Javascript provides many built-in array functions for getting tasks done quickly and in an efficient way. Javascript filter() function is one of those popular functions used to iterate over an array’s elements and get the desired result.

In this post, we will grasp the concept of the javascript filter() function. What is a filter() function, and how can we use it to help in simplifying the Javascript code and complete the tasks efficiently and most quickly.

What is the filter function in JavaScript

Javascript’s filter() function for the array is used to filter out the data based on the given condition or test.

  • The filter() function takes the element of an array one by one and applies the condition on each element.
  • The filter() function keeps the elements that pass the condition in a different array and return the resulting array after iterating through the whole array.
  • This filter() function of the array does not affect the original array.

Let’s explore more into it to understand the syntax and its functionality, along with a couple of examples.

Syntax of filter function in JavaScript

array.filter(function_name, thisValue);

Array’s filter() function takes a function as a callback function with three arguments. The syntax of the callback function and the sequence of arguments will go like this:

function function_name(value, index, array)

   return condition;

In the call back function of filter() method:

  • The first parameter is the current value of the array element during the iteration.
  • The second parameter is the optional parameter which is the current index of the array element during the iteration.
  • Lastly, we can also pass the array itself to the callback function for having some custom functionalities inside the callback function.

We can also pass “thisValue” to the function, where the “this” keyword refers to the parent block/object.

Now we will use a couple of examples to see its real-life implementations.

Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:

  • Use the F12 key in Chrome and other chromium-based browsers.
  • Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
  • Use Option + ⌘ + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing ⌘ +, and in Advanced tab check “Show Develop menu in menu bar”).

How to use filter() function in JavaScript

The best example to understand the filter() function is to filter some numbers from an array of numbers based on the given condition.

Example 1:

Suppose we have an array of numbers and we want to get numbers greater than some specific number:

var numbers = [23,16,38,5,10,19]

The first method to get the desired range of numbers is to loop through the whole array and put a condition inside the loop to check whether the number passes the given test (greater than 18 or not). If the number passes the test, it will be added/appended to a new array. The code of the for loop for filtering out the numbers is given below:

varfilteredArray = [];

for (leti = 0; i18)
filteredArray.push(numbers[i])
 
}

console.log(filteredArray);

In the above code, we first put a loop over the “numbers” array, then put a condition using the if statement, and if the array element passes the condition, it will be appended/pushed to the “filteredArray” variable.

Although we have got the desired range as output. But, why not use a smart and easy way to get the filtered Array using the filter() method of the array, where we do not have to mutate the variables like “filteredArray.”

Use of filter() function

The filter() function to get the numbers greater than 18 will go like this:

varfilteredArray = numbers.filter(getAdults);

functiongetAdults(n)
    return n >18;

console.log(filteredArray);

In the above-given code, you can see that we have first passed the “getAdults” function to the filter() function, and in the “getAdults” function definition, we just checked whether the number is greater than 18 or not and if this condition returns true then return that array element.

Once the “filter” function checks all the numbers in the “numbers” array, it will store the final result in the “filteredArray” variable.

Lastly, we have just consoled the “filteredArray” variable to verify whether our filter() function worked fine or not.

You can verify by looking in the screenshot provided above that the filter() function has returned all the numbers which are greater than 18.

Another shorter and easier way to write filter() function is to make the callback function of filter() function an arrow function:

The syntax of writing the callback function within the filter() function’s parentheses will be like this:

varfilteredArray = numbers.filter((n) =>
return n >18
);

console.log(filteredArray);

Alright, this was the simple example in which we have an array of numbers only; what about the array of objects. Let’s try that one as well.

Example 2:

Suppose we have a list of students in an array, and we want to get the list of the students whose fees are above $8000:

var students = [
   
        id: 1,
        name: “John,”
        age: 12,
        fee: 8500
    ,
   
        id: 2,
        name: “Bob”,
        age: 15,
        fee: 4500
    ,
   
        id: 3,
        name: “Steve”,
        age: 10,
        fee: 7500
    ,

        id: 4,
        name: “Harry”,
        age: 13,
        fee: 10500
    ,
   
        id: 5,
        name: “Tom”,
        age: 14,
        fee: 9000
    ,
   
        id: 6,
        name: “Ron”,
        age: 11,
        fee: 6000
    ,
]

The filter() function to get the filtered list of students will go like this:

varfilteredStudents = students.filter((student) =>
returnstudent.fee> 8000
);

console.log(filteredStudents);

Now, the only difference in this code is that a single object is passed as a value to the callback function, and inside the definition of the callback function, we put a condition and return the object where the student’s fee is greater than $8000.

By looking at the screenshot attached above, you can see that students’ fees are greater than $8000 and are displayed as an output. So this is how we can access the objects of an array in the filter() function.

Conclusion

In this post, we have learned what a filter() function is and how we can use it to help in simplifying the Javascript code.

We have learned that the filter() function filters out the array elements based on the given condition. The filter() function takes the element of an array one-by-one, takes a callback function applied to every element of the array, and returns the new filtered array.

This post is all about JavaScript’s filter() function and its usage. It contains some basic examples that help in understanding filter() function easily.

Leave a Reply

Your email address will not be published. Required fields are marked *