In this article, we will be taking a deep dive into Javascript arrays and the Array filter concept. We will delve further into how a filter function works in JavaScript to the arrays to get the desired output.
What are Arrays in JavaScript?
Arrays are linear data structures used to store homogenous data, i.e. same type of data. An array can contain all integers, all characters, or all strings as the elements. An array can not be a combination of integers and characters, or integers or strings. Let us take a look at how to declare and use arrays in Javascript.
//declaring an integers array
let marks = [98, 75, 62, 82, 97, 53];
//declaring a characters array
let grades=['A', 'B', 'A', '0'];
//declaring a strings array
let favtutors=["John", "Joshua", "Alex", "Kate"];
//declaring a boolean array
let present=[true, false, false, true];
In the code above, we have made integers array marks containing all integers, a characters array grade consisting of all elements as characters, a strings array ‘favtutors’ consisting of all strings, and a boolean present array consisting of all boolean values.
What is meant by Filter?
Now we know what JavaScript Arrays are. Let’s say we have an array of marks depicting the marks of students in a particular class. What if we want to store the marks of students scoring above 90? Basically, we want to filter out the marks that are above 90.
One easy way would be to declare a new array, let’s say marksabove90. Now, we traverse the initial marks array and check each value/element if it is more than 90. If it is, we add it to the new array marksabove90, else, we don’t.
We get the final array marksabove90 containing the marks above 90, after traversing the whole array. So, we have separated the marks greater than 90. The code is given below:
//declaring an integers array let marks = [98, 75, 62, 82, 97, 53]; //declaring an empty array to store marks that are above 90 let marksabove90=[]; //traversing the array to check if marks are greater than 90 for(let i=0;i<marks.length;i++){ //condition to check if marks[i] is greater than 90 if(marks[i]>90){ //adding the marks[i]>90 in the marksabove90array marksabove90.push(marks[i]); } } //printing the marksabove90array console.log(marksabove90);
Output:
[ 98, 97 ]
Arrays filter() Function in Javascript
Before we discuss this inbuilt function, one should know about the callback function.
Have you ever used custom comparator functions in sorting an array in C++? It is one example of a callback function. A callback function is a boolean function that is passed as an argument to another function and is intended to be executed after the completion of that function.
The filter() function is a powerful array method in JavaScript that allows one to create a new array containing elements that satisfy a specific condition. It iterates over each element of an array and applies a callback function to determine whether the element should be included in the filtered array.
The callback function is a boolean function. If it returns true for an element, it is pushed into the new array. If it returns false, it is not added.
The syntax of the filter() method is given below:
array_name.filter(callback_function);
The syntax of the filter() method with optional elements that might prove useful in some cases.
array_name.filter(callback_function(element, index, array_name), thisValue);
Parameters:
- array: The array on which the filter() method is called.
- callback: A function that is executed for each element of the array.
- element: The current element being processed.
- index (optional): The index of the current element.
- array (optional): The array on which the filter() method is called.
- thisValue (optional): The value to be used as this when executing the callback function.
Note that the filter() method is a standard ECMAScript 5 (ES5) feature and is supported in all modern browsers. However, for older browsers, such as Internet Explorer 8 and below, this method is not supported.
Example of Array filter() Method
Now, we know the syntax of the filter() method that uses a callback function inside it. So, let us take the previous example of creating a new array containing marks>90.
//declaring marks array let marks = [98, 75, 62, 82, 97, 53]; //declaring marksabove90 and storing marks above 90 in it using the below method let marksabove90= marks.filter(function(element) { return element >90; }); //printing marksabove90 array console.log(marksabove90);
Output:
[ 98, 97 ]
In the above example, we have used the inbuilt filter() function which calls a function inside it. The function is a call-back function, which takes every argument of the original marks array and checks for each element if it is greater than 90 or not.
It returns a boolean value true if the element is greater than 90 and hence adds it into the array. If it returns false, no action is taken, and that element is not added to the array
Using the Arrow Function
We can also use the arrow function in the above code. An arrow function is a concise way to write anonymous functions (functions that do not have a name) in JavaScript.
//declaring marks array let marks = [98, 75, 62, 82, 97, 53]; //declaring marksabove90 array and storing marks above 90 in it using the below method //using arrow function instead of the whole definition of the function let marksabove90 = marks.filter((element) =>element >90); //printing marksabove90 array console.log(marksabove90);
Output:
[ 98, 97 ]
In this example, the callback function ((element) => element > 90) checks if each element in the array is greater than 90. If the condition is true, the number is included in the filtered array marksabove90.
Filtering Objects in an Array
The filter() method can also be used to filter objects in an array based on specific criteria.
Let us take an example. We define an array of objects as “student”. The object has various properties like name and marks.
//declaring an array of "students" objects const students = [ { name: 'Josh', marks: 98 }, { name: 'Alex', marks: 75 }, { name: 'Kate', marks: 62 }, { name: 'John', marks: 82 }, { name: 'Cole', marks: 92 }, { name: 'Drew', marks: 53 } ]; //applying filter() function along with callback function let marksabove90= students.filter((student) => student.marks > 90); //printing modified array console.log(marksabove90);
Output:
[{name: 'Josh', marks: 98 }, {name: 'Cole', marks: 92 } ]
The filtered array contains the students whose marks are above 90.
Important Points to Keep in Mind
- When the filter() function is applied to an empty array, it will always return an empty array. Therefore, there arises a need to check the filtered array before further processing.
- Thid method never modifies the original array, instead, it returns a new array consisting of elements that return true in the callback function.
- It’s important to note that the callback function is invoked for each element of the array. If the callback function is complex or performs expensive operations, it can impact the performance of your application. Consider optimizing the callback function if necessary.
Conclusion
In this blog, we have discussed all about the JavaScript Array filter() method to refine the elements according to some specific criteria. It is very important to keep the important points in mind to use this function effectively.