DEV Community

Cover image for JavaScript’s Filter Function Explained By Applying To College
Kevin Kononenko
Kevin Kononenko

Posted on • Updated on

JavaScript’s Filter Function Explained By Applying To College

If you are familiar with the college application process, then you can understand JavaScript’s filter functions.

Compared to the map() and reduce() methods in JavaScript, the filter( )method has probably the most straightforward name.

You input an array, and you filter out the elements that fulfill a specific condition into a new array.

This seems simple, but I always seemed to find myself reverting to for() loops. So, I decided to find a better way to understand how filter() functions worked.

I realized that filter functions are kind of like a college admissions officer. They use a set of parameters to decide which students should be admitted to their particular college. Yes, we all wish that colleges were a little more flexible and judged our accomplishments holistically, but in reality, most still have hard numbers around SAT, ACT and GPA scores that determine who will be considered.

Let’s get into it!

Using A For Loop Instead of Filter Function

Okay, let’s say that we have an array of 4 students with names and GPAs. This particular college only wants to admit students with a 3.2 GPA or higher. Here is how you might do that.

let students = [
  { 
    name: "david", 
    GPA: 3.3 
  }, 
  { 
    name: "sheila", 
    GPA: 3.1 
  }, 
  { 
    name: "Alonzo", 
    GPA: 3.65 
  }, 
  { 
    name: "Mary", 
    GPA: 3.8 
  }
] 

let admitted =[]; 

for (let i=0; i < students.length; i++){ 
  if(students[i].gpa > 3.2) 
    admitted.push(students[i]); 
} 

/*admitted = [
  { 
    name: "david", 
    GPA: 3.3 
  }, 
  { 
    name: "Alonzo", 
    GPA: 3.65 
  }, 
  { 
    name: "Mary", 
    GPA: 3.8 
  }
];*/
Enter fullscreen mode Exit fullscreen mode

Wow! That was way more complicated than it needed to be. If someone was reading over your code, they would need to track multiple arrays just to learn that you were simply filtering one array into another. And, you need to carefully track i as you go in order to avoid any bugs. Let’s learn how to use the filter method to accomplish the same thing.

Using the Filter() Method

Let’s learn how to accomplish the same goal with the filter() method.

  1. Filter is an array method, so we will start with the array of students.
  2. It uses a callback function that runs on each element in the array.
  3. It uses a return statement to show which elements will actually end up in the final array, in this case, the admitted students.
let students = [
  { 
    name: "david", 
    GPA: 3.3 
  }, 
  { 
    name: "sheila", 
    GPA: 3.1 
  }, 
  { 
    name: "Alonzo", 
    GPA: 3.65 
  }, 
  { 
    name: "Mary", 
    GPA: 3.8 
  }
] 

let admitted = students.filter(function(student){
   return student.gpa > 3.2;
})

/*admitted = [
  { 
    name: "david", 
    GPA: 3.3 
  }, 
  { 
    name: "Alonzo", 
    GPA: 3.65 
  }, 
  { 
    name: "Mary", 
    GPA: 3.8 
  }
];*/
Enter fullscreen mode Exit fullscreen mode

The inputs and outputs are the same, so here’s what we did differently:

  1. We didn’t need to declare the admitted array and then fill it later. We declared it and then filled it with elements in the same code block
  2. We actually used a condition within the return statement! That means that we only return elements that pass a certain condition.
  3. We can now use student for each element in the array, rather than students[i] like we did in the for loop.

filterDiagramV1.jpg

filterDiagramV2.jpg

You may notice that one thing is counterintuitive- getting admitted to college is the last step, but in our code, the variable admitted is the first part of the statement! You might usually expect to find the final array as the last statement within the function. Instead, we use return to indicate which elements will end up in admitted.

filterCodeBlock1.jpg

Example 2- Using Two Conditions Within Filter

So far, we have just used one condition in our filter methods. But that does not represent the college admission process at all! Usually, admissions officers are looking at 10+ factors.

Let’s look at two factors- GPA and SAT scores. Students must have a GPA over 3.2 and an SAT score over 1900. Here is what the same function would look like.

let students = [
  {
    name: "david",
    GPA: 3.3,
    SAT: 2000
  },
  {
    name: "sheila",
    GPA: 3.1,
    SAT: 1600
  },
  {
    name: "Alonzo",
    GPA: 3.65,
    SAT: 1700
  },
  {
    name: "Mary",
    GPA: 3.8,
    SAT: 2100
  }
]

let admitted = students.filter(function(student){
   return student.gpa > 3.2 && student.SAT > 1900;
})

/*admitted = [
  {
    name: "david",
    GPA: 3.3,
    SAT: 2000
  },
  {
    name: "Mary",
    GPA: 3.8,
    SAT: 2100
  }
];*/
Enter fullscreen mode Exit fullscreen mode

Looks pretty similar, right? Now we just have two conditions within the return statement. But let’s break that code down a bit further.

let admitted = students.filter(function(student){
   let goodStudent = student.gpa > 3.2 && student.SAT > 1900
   return goodStudent;
})
Enter fullscreen mode Exit fullscreen mode

Aha! So here is another important difference when compared to for loops. If you check out the goodStudent variable, you can see that it will only evaluate to true or false. Then, that boolean is fed into the return statement.

So, that true or false really just decides if each member of the original array will be included or not in the resulting array, admitted.

twopartfilter1.jpg

twopartfilter2.jpg

Get More Visual Tutorials

Did you enjoy this tutorial? You will probably also enjoy my other visual explanations of web development topics on the CodeAnalogies blog.

Top comments (10)

Collapse
 
bojanorter profile image
bojanorter • Edited

For filtering like this,

let admitted = students.filter(function(student){
   return student.gpa > 3.2 && student.sat > 1900;
})

i would use arrow functions new in ECMAScript 6.

then this becomes

let admitted = students.filter(student => 
student.gpa > 3.2 && student.sat > 1900
})

Other than that, I liked your post.

Collapse
 
kbk0125 profile image
Kevin Kononenko

Yeah, it is always tough for me to decide which version to use, maybe I just need to start including the second version in comments :)

Collapse
 
kamalhm profile image
Kamal • Edited

this is nice! Thanks!

edit

you should fix the typo in the student attributes, because it's case sensitive

Collapse
 
kbk0125 profile image
Kevin Kononenko

Thanks Kamal! which one are you talking about?

Collapse
 
iksworks profile image
Ishmael Sunday • Edited

Some of the names start with caps and other don’t. They all should start lower or uppercase for consistency.

Also in your explanation, you said they need 3.2 or up. The function is not considering 3.2. You used (>) which excludes 3.2. Should it be >= ? You might want to as “s” word student in the return. students.gpa etc.

I am just a beginner. Starting my first JS class on the 18th. Thanks for the article too.

Thread Thread
 
kbk0125 profile image
Kevin Kononenko

Hey Ishmael, yep, you are correct about the 3.2 thing. As for "students" v. "Students", I tried to use the uppercase when referring to actual students, and lowercase when referring to the students array.

My original article uses interactive images that make this a little more clear:

blog.codeanalogies.com/2018/05/14/...

Collapse
 
kamalhm profile image
Kamal

Instead of student.sat you should change it to student.SAT

Thread Thread
 
kbk0125 profile image
Kevin Kononenko

Good point. Fixed the SAT issues.

Collapse
 
cyberfly profile image
Muhammad Fathur Rahman

thanks great sharing

Collapse
 
delimanicolas profile image
Nicolas Lima

Nice article!