Codementor Events

JavaScript’s Filter Function Explained By Applying To College

Published Jun 03, 2018Last updated Nov 30, 2018
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 
  }
];*/

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 
  }
];*/

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
  }
];*/

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;
})

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.

Discover and read more posts from Kevin Kononenko
get started
post commentsBe the first to share your opinion
amrithraj
6 years ago

Hi Kevin,

I like the way of explaining the concept .It is very easy to understand.

Rob Muhlestein
6 years ago

Or…

let admitted = students.filter(  _ => _.gpa > 3.2 && _.sat > 1900)
Kevin Kononenko
6 years ago

Rob, I am assuming you are saying I should be using arrow functions. I am always torn on whether to use them or not in these tutorials, I do get a lot of people telling me to do so :)

Rob Muhlestein
6 years ago

I have the same challenge. Beginners clearly understand the function keyword for easily. But after doing an entire project using PWA and new ES6 compiled with Babel and Gulp (the standard still imho) I am 100% sold on them. Understanding them takes a bit of explanation and experience, but they are so key to the new functional and event-driven paradigms taking solid root in modern programming.

In other words, yes.

Rob Muhlestein
6 years ago

As soon as you write any amount of concurrent code with Promises and callbacks the removal of tons of function keywords, paratheses, and brackets just become so beautiful. I am also now a (converted) anti-semicolon proponent (https://standardjs.com/). }) occurs so frequently now, and it’s beginning is often off the screen, so remembered with to }); and when to }) is “too much cognitive overhead” to steal another educators catch phrase.

Rob Muhlestein
6 years ago

My favorite thing from watching all of Paul Irish’s Google presentation was his practice of using underscore for functions taking zero or 1 argument:

const greet = _ => 'Hello, ' + _ 
ALI ARHAM
6 years ago

I like your way explaining.It is very simple and easy to understand. But i could not console log your codes.could you please send me the three console logs. I would be thankful to you for this act of kindness. thanks a lot.

Kevin Kononenko
6 years ago

Hey Ali, can you tell me which specific statements you are referring to?

Show more replies