Array Filter in JavaScript

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.

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:

  • Filter’s first argument is a callback function that exposes these parameters:
    • value (the current element)
    • index (the element’s index - sometimes used with Filter)
    • array (the array we are looping - rarely used)
    • Inside the body of the function we need to return an expression which will evaluate to a Boolean (true or false)
  • Filter’s second argument thisArg allows the this context to be changed

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.

 


 

#js #javascript 

Array Filter in JavaScript
1.00 GEEK