How to filter() your school lunch because nobody wants meatloaf

How to filter() your school lunch because nobody wants meatloaf

The filter array method creates a new array with all the items that pass the test given by the function you gave it. By the end of reading this article, you'll get a deeper understanding of how to filter arrays of numbers, strings and an array of objects. You'll be on the A/B honor roll, for sure.

It's elementary my dear Watson...

Let's take a look at some numbers I have in an array.

const scores = [85, 50, 22, 64, 100, 93]

Now let's say our 5th grade math teacher is letting us remove all grades lower than a 60 from our recent test scores. Great! But we have to prove we 5th graders know how to filter an array. Fear not, here's how.

const oldScores = [85, 50, 22, 64, 100, 93]
const newScores = oldScores.filter( item => item > 60 )
console.log(newScores)
// Array(4) [ 85, 64, 100, 93 ]

Success! Let's see what we did though, not time for recess yet.

So in our variable oldScores we have our old test scores in that array. That array had two scores that had a value less than 60.

In newScores we are using the filter() array method on the variable oldScores. Look inside the parentheses:

 item => item > 60

The filter() array method accepts a callback function (the bold function inside our parentheses). That callback function wants to coerce each item in the array to be truthy. We are testing each item in the variable oldScores to be greater than 60.

A note to realize is the filter method not only creates a new array for you to use, but it traverses (or moves on down the line) over the array given to the method (in this case oldScores).

When the filter() method traverses over the item in oldScores it will test each item's index against that function. Anything that returns 'true' gets put into the new array that's created. Anything that tests false is not used in the new array. And you guessed it, it's assigned to newScores after the traversing of the array is complete. Take not also, we are not modifying the oldScores array at all.

Extra credit

Ok kids, grab your juice boxes, we're going to kick it up a notch.

What if you wanted to filter an array of objects based on the property's value? For instance, the teacher has some records of a few students. This record is an object that has their name and average score.

Something like this:

const students = [
{
name: 'Tommy',
avgScore: 89
},
{
name: 'Angelica',
avgScore: 93
},
{
name: 'Chuckie',
avgScore: 98
},
{
name: 'Phil',
avgScore: 83
},
{
name: 'Lil',
avgScore: 83
}
]

Let's say our teacher needs to give awards to those who have an average score of 85 and above. How would we filter this array? Like so:

const awards = students.filter( item => item.avgScore >= 85 )
console.log(awards)

And you would have awards equaling this:

Screen Shot 2021-02-01 at 10.53.33 PM.png

Phil and Lil unfortunately just missed the mark, but better luck next time.

The first argument the callback function we've named item. We could have used the word 'student' or 'x' or whatever. So long as what's right of the fat arrow correlates with the word of the argument we are passing in. In this case we are wanting to specifically test the avgScore property value of the object we are traversing over. And we want all avgScore values to be equal to or greater than 85. So we use the equal to or greater than comparison operator in between item.avgScore and the number 85. And bingo, we have a new array with just 3 of the 5 students who's average score is 85 or higher.

If you want to learn more about comparison operators check out MDN's docs on it at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison_operators

I would do anything for lunch, but I won't do that...

We've been working numbers, but you can also filter arrays based on string values like so:

const lunch = ['pizza', 'meat loaf', 'milk', 'corn dog']
const filteredLunch = lunch.filter( item => item !== 'meat loaf' )
console.log(filteredLunch)

Screen Shot 2021-02-01 at 11.03.45 PM.png

So since the school meat loaf looks like road kill, we're going to filter it our of our lunch array. Once again, the original lunch array is left untouched in our program, but the variable filteredLunch has what we want, so let's dig in!

School's out!

In summary, the filter method is a great way to create a new array with only the items you want in it. Just pass a function that tests each item in the array. Whatever is truthy is put into a new array for you to use. Now if you'll excuse me, I'm going to trade my Fruit Roll Ups for some Gushers. Peace!