Get super confident at JavaScript. Javascript Icon

I promise to change your JavaScript skills!

Exploring Array Filter in JavaScript

Follow along with the Exploring JavaScript Array Methods series!

What is Array Filter?

Array Filter is a method that exists on the Array.prototype that was introduced in ECMAScript 5 (ES5) and is supported in all modern browsers.

Array Filter allows us to conditionally return certain elements from our array, into a new array. It’s commonly used to remove items from an array by excluding them from the result.

Think of Array Filter as: “I want a new array containing just the items I need”

With each iteration of a Filter loop, you will need to return an expression that Filter evaluates either true or false.

Angular Directives In-Depth eBook Cover

Free eBook

Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.

  • Green Tick Icon Observables and Async Pipe
  • Green Tick Icon Identity Checking and Performance
  • Green Tick Icon Web Components <ng-template> syntax
  • Green Tick Icon <ng-container> and Observable Composition
  • Green Tick Icon Advanced Rendering Patterns
  • Green Tick Icon Setters and Getters for Styles and Class Bindings

The key to understanding Filter is to realise your callback is returning an expression that will evaluate to true or false.

Array elements that evaluate to true are stored in a new array - and items that evaluate to false are excluded. Once Filter has completed, you can access the new array of your values.

Here’s the syntax for Array Filter:

const returnValue = array.filter((value, index, array) => {...}, thisArg);

Our returnValue will contain our new array of filtered return values.


Array Filter syntax deconstructed:

See the ECMAScript Array Filter specification!


In its simplest form, here is how Filter behaves:

const array = [true, true, false];

// [true, true]
console.log(array.filter(Boolean));

Array Filter expects us to return an expression that will evaluate true or false, we can go straight to the finish line and make it easier by supplying literally true and false array values.

I’m using JavaScript’s Boolean object to coerce the array element to a Boolean. As our array already contains Boolean values, any false values are omitted.

Notice how Filter is also returning multiple values, compared to its closely related sibling method Array Find.

Using Array Filter

Here’s our data structure that we’ll be using Array Filter with:

const items = [
  { id: '🍔', name: 'Super Burger', price: 399 },
  { id: '🍟', name: 'Jumbo Fries', price: 199 },
  { id: '🥤', name: 'Big Slurp', price: 299 }
];

Here let’s assume we want to create a new array of more expensive items in this array, we can consider “expensive” to be 199 and above.

Let’s return an expression now that compares each item’s price property with greater than > 199, which aims to filter out values that aren’t considered expensive:

const expensiveItems = items
  .filter(item => item.price > 199);

This would then give us the two items that are considered “expensive” based on our 199 threshold value:

[
  { id: '🍔', name: 'Super Burger', price: 399 },
  { id: '🥤', name: 'Big Slurp', price: 299 }
]

Interestingly, our original items array remains unmodified, and we have a new collection to deal with now in our expensiveItems variable. This practice is called an immutable operation as we don’t mutate the initial array.

Give the live demo a try:

Bonus: Filter-ing without Filter

Let’s check out a for…in loop example that mimics the behaviour of Array Filter:

const expensiveItems = [];

for (let i = 0 ; i < items.length; i++) {
  const item = items[i];
  if (item.price > 199) {
    expensiveItems.push(item);
  } 
}

First we declare expensiveItems as an empty array. Inside the loop we use pretty much the same logic, but instead of a return statement we use the Array.prototype.push method which adds each item to the new expensiveItems array.

Once the loop as finished, you’re free to work with your new filtered array.

Summary

You’ve now learned how to use Array Filter to filter your array to a specific set of values.

You can think of Filter of like a functional “if statement”. If my array element meets my criteria - give it to us… Else, we don’t want it.

If you are serious about your JavaScript skills, your next step is to take a look at my JavaScript courses, they will teach you the full language, the DOM, the advanced stuff and much more!

Angular Directives In-Depth eBook Cover

Free eBook

Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.

  • Green Tick Icon Observables and Async Pipe
  • Green Tick Icon Identity Checking and Performance
  • Green Tick Icon Web Components <ng-template> syntax
  • Green Tick Icon <ng-container> and Observable Composition
  • Green Tick Icon Advanced Rendering Patterns
  • Green Tick Icon Setters and Getters for Styles and Class Bindings

Further tips and tricks:

Thanks for reading, happy Filtering!

Go to the next article in Exploring JavaScript Array Methods - Array Reduce!

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover