RxJS icon Launch Deal: Get $100 off the RxJS Kickstart Bundle now!

RxJS Masterclass is here. 2-course bundle - buy now (discount applied at checkout).

days
hours
mins
secs

Exploring Array Filter in JavaScript

Mar 25, 2020 8 mins read

JavaScript post
JavaScript icon

Want to level up your JavaScript skills? Who doesn't. Here's what you need to know

Show Me View JavaScript courses

Welcome to the third article in this series where you will learn how to use the array prototype method - Filter! In this article, you’ll learn how, when and why you should use Filter that covers a lot of real-world tips and common pitfalls developers new to Filter typically have.

Follow the Array Prototype Series!

You can also follow along with the rest of this series of posts on Array prototype methods:

Not only will you uncover all common practices and syntax you need to use on a daily basis, I’ve also included a lot of hints and tips from over the years writing JavaScript.

Now it’s time to dive into array Filter!

What is Filter?

Filter is a method that exists on the Array.prototype. It provides a way for us to remove items from an array that don’t pass a test that we specify. Filter will iterate your array and perform a test on each element to see if it passes. If it passes, you get it back as part of a new array.

Each test (done in the callback function) must return a value that can be evaluated to true or false. All you need to think about is whether your code returns a value that will be evaluated to true or false. Those true values are then given back as a new array and those false values are disposed of (the initial array you filter from remains untouched however - and that’s a good thing).

The practice of testing array elements and constructing a new array is typically referred to as “filtering”. We want to filter the good things out. If it passes the test condition, give me it back in an array!

You can almost think of Filter as a functional programming “if” statement. Logic that you’d typically write if (<HERE>) {} would go in your filter - that’s the easiest way to remember it.

Here’s the syntax for the Filter method in JavaScript:

const returnValue = array.filter(callback[, thisArg])

Filter was introduced in ES5 as a new helper method. I’d encourage you to also read the Array.prototype.filter specification.

The first argument is a callback function, which is given three arguments, currentValue, the index and the current array. Filter’s callback function is invoked on every item in the array, passing us the item in the array (as well as it’s index as a second argument, if needed).

The second is the (optional) this context, should you wish to pass a new object as a reference to change the execution context.

In its simplest form, here is how Filter behaves:

const array = [true, true, false];

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

I’m using JavaScript’s Boolean object here to coerce the result to a Boolean. As our array already contains Boolean values, the false value is omitted from the results.

Using Filter in JavaScript

In this next section, we’ll explore when to use Filter and look at some array Filter examples in JavaScript. I’ve also thrown in an example of how to Filter without Array.prototype.filter so you can compare the “old” way of doing things!

When To Use Filter

The time to reach for Filter is when you need to remove items from an array, that you don’t want. Filter will return you a new array of the items you do want after you supply it a test.

Our test could be as simple as “is this item greater than 10?”.

Numbers could then be evaluated one-by-one to see if they are greater than 10. Those that are greater, you’ll get back in a new array. References of items in your new array are shallow-copied.

Generally, Filter is a really common method to use with your data structures to return items for further processing - such as testing the value of a specific object property and doing something with just those returned values.

As Filter accepts a callback function, it’s important to note that this will create new function scope. A traditional filtering approach via a for...in will not create new function scope on each iteration.

Array Filter example

Let’s look at how we can loop over array elements using Filter. Here’s our data structure, a nice array with some objects inside:

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

A most basic Filter gives us each item in our array, as well as its index position (if you need it!).

Let me demonstrate how we can use Filter to simulate an amended order - perhaps the user has changed their minds and wants to remove the Jumbo Fries '🍟' from their cart (upon clicking remove, we could have a callback that executes the following code):

const amendedOrder = items.filter(function(item) {
  return item.id !== '🍟'
});

// log the return value!
console.log(amendedOrder);

The above output would then give us:

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

Note how we return inside (like Map) and make a comparison. If the item.id is not equal to '🍟' then return that item - otherwise Filter will omit it and not return '🍟' to the new array. Our item.id could be a unique database ID in a production environment.

As Filters tend to be short comparisons, you’ll likely see them in the wild with a concise arrow function:

const amendedOrder = items.filter((item) => item.id !== '🍟');

With our new knowledge of Array Map, we could also transform the new filtered array into a new array of strings which contain each item.name, so we can display something more readible for the user:

console.log(`Amended Order: ${amendedOrder.map(item => item.name).join(', ')}`);

Check it out:

The good news is that we’ve created a new array and our original items remains untouched. We have a new filtered collection now that we can do something with.

That was pretty easy to filter an entire data structure and omit any array elements we like (without mutating the existing array)! This practice of creating new arrays intead of mutating an existing array is called an “immutable operation”. A mutable operation would mutate the initial array, whereas we leave it untouched always. I hope this opens up some doors for you in your JavaScript programming.

Bonus: Filtering without Filter

Using a for...in approach, here’s traditionally what one would have to write to filter an array without the Filter method. Here’s a side-by-side comparison of the newer array Filter approach versus the traditional imperative filter:

// Declarative approach: Array.prototype.filter
const amendedOrderDeclarative = items.filter((item) => item.id !== '🍟');

// Imperative approach: Filtering an array
const amendedOrderImperative= [];

for (let i = 0 ; i < items.length; i++) {
  const item = items[i];
  if (item.id !== '🍟') {
    amendedOrderImperative.push(item);
  }
}

Both amendedOrderDeclarative and amendedOrderImperative will contain identical values.

This also demonstrates us the power and flexibility of using Filter and other array prototype methods. The code is far smaller, promotes better practices, is easier to read and far more contained.

Note “Declarative approach” and “Imperative approach”. Declarative follows a more functional programming style which uses pure functions. Pure functions are easier to reason with, provide nice unit testing and allow us to chain operations together through a series of operators such as .filter().map().

The Filter operator also produces new shallow copies of your array rather than mutating existing arrays. These practices tend to be preferred by the community as they produce no unintended side-effects (that may occur with more traditional code patterns and practices).

Summary

Filter is a great method for mastering your JavaScript loops. Moving from a traditional for...in loop, the Filter method can be introduced to bring a more functional approach and style to your programming.

If you’re enjoying this series, please keep following! To learn more JavaScript practices at this level and comprehensively, I’ve put together some online videos that explore the entire JavaScript language and the DOM - I’d encourage you to check them out if you are serious about JavaScript.

You’ve now learned how to use a Filter to run a test on your array, that each element must pass to become part of the new array! Here’s a brief recap of what we’ve talked about and some extra details:

  • Filter can be used to return specific values, they will evaluate to true or false
  • Don’t forget to return or your values will be undefined which coerces to false (so an undetected bug could be introduced!)
  • The easiest way to get all truthy values in the array is by using .filter(Boolean)
  • You can access the array you’re looping in the third argument of the callback
  • You can change the this context via a second argument to .filter(callback, thisArg) so that any references to this inside your callback point to your object
  • You can use arrow functions with Filter but remember that this will be incorrect if you also supply a thisArg due to arrow functions not having a this context
  • Using Filter will skip empty array slots as if it were a falsy value
  • You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary

Thanks for reading, happy filtering!

Go to the next article in this series - Exploring Array Some!

Love the post? Share it!

Lots of time and effort go into creating all our blogs, resources and demos, we'd love if you'd spare a moment to share this one!