Page 1 of 1

Learn How to Filter Data in JavaScript

Posted: Sun Feb 02, 2025 7:16 am
by soniya55531
JavaScript icon used as backgroundThree images of JavaScript course classes
Learn How to Filter Data in JavaScript
In today's lesson, I want to show you how to filter data in JavaScript! The process of filtering information is crucial, not only in JavaScript, but in any language. It allows us to separate, analyze, and validate the data we are working with.

Filtering provides options to drill down into information without having to deal with the entire database, focusing only on the necessary data.

So, come with me and I'll show you how to easily filter data in JavaScript, so you can access only the information you want whenever you need it!

Filter Data in JavaScript – Filtering Approved Students
Within JavaScript, we have the filter method that is used to select elements within an array that meet a certain condition.

This method will evaluate each element of the array according to the established condition and, after filtering, will return the elements that satisfy this condition.

To see this method in practice, we will use an example line data similar to the one in the last lesson when we discussed the map method in JavaScript. We will have an array with the students' grades and we will define an average of 6 as the minimum grade to pass.

Within the filter method, we define the criteria for filtering the data. In this case, we are using a boolean expression that will return true if the student's grade is greater than or equal to 6 and false otherwise.

By executing this code, we will have the array listaNotas displayed , with all the grades, and notasAprovadas , containing only the grades that are greater than or equal to 6.

Filtered array
Second Example for Filtering Data in JavaScript
The filter method is very versatile and can be applied in many scenarios beyond just numbers in arrays.

We can, for example, use the filter method to select students with an average equal to or greater than 6, from a list of objects with two different grades.

In this case, we are creating an array of objects , where each object represents a student and has two properties: grade1 and grade2 , representing each of the grades.

To filter the approved students, we are defining within the filter method a function that calculates the students' average, adding the two grades and dividing by 2. If the average is greater than or equal to 6, the function returns true , otherwise, it returns false .

By running this code, we can see two lists: one with all the grades and the other with only the students with an average greater than 6.