30 Days Of JavaScript

Day 10: Higher Order Functions Part 1

Lesson 4: filter

Next up is .filter() this does exactly what you would expect, filters an array based on whatever function you pass into it.

The function you pass into .filter() should return true if the item should be kept in the array and false if it should not be included.

Let's filter out people below 18 in this array:

Again, I've use the shorthand syntax here as it's very common when using higher order functions, the longer form version of this looks like this:

Change the age above to be older than the oldest person (so at least 33), what do you think you'll get back?

You get back an empty array.

Some people get confused by this. It's an empty array (rather than an error or warning) because an array with no items in it, is still a valid response from a filter. In this example if no number is larger than the one you filter by then an empty array is the correct response.

That's really all there is to filter.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co