// Tutorial //

How To Use the filter() Array Method in JavaScript

Published on September 3, 2020 · Updated on August 26, 2021
Default avatar
By Ceferino IV Villareal
Developer and author at DigitalOcean.
How To Use the filter() Array Method in JavaScript

Introduction

The filter() Array method creates a new array with elements that fall under a given criteria from an existing array.

In this article, you will learn about the filter() Array method.

Prerequisites

If you would like to follow along with this article, you will need:

Using filter() on an Array of Numbers

The syntax for filter() resembles:

var newArray = array.filter(function(item) {
  return condition;
});

The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects.

If the current item passes the condition, it gets returned to the new array.

Consider this example array of numbers:

var numbers = [1, 3, 6, 8, 11];

Then apply a filter() to return all numbers that are greater than 7:

var greaterThanSeven = numbers.filter(function(number) {
  return number > 7;
});

console.log(greaterThanSeven);

This code will generate a new filtered array:

output
[8, 11]

An array with two values greater than 7 is returned.

Using filter() on an Array of Objects

A common use case of filter() is with an array of objects through their properties.

Consider this example array of creature objects:

var creatures = [
  {name: "Shark", habitat: "Ocean"},
  {name: "Whale", habitat: "Ocean"},
  {name: "Lion", habitat: "Savanna"},
  {name: "Monkey", habitat: "Jungle"}
];

Then apply a filter() to return all creatures with a habitat that is equal to Ocean:

var aquaticCreatures =  creatures.filter(function(creature) {
  return creature.habitat == "Ocean";
});

console.log(aquaticCreatures);

This code will generate a new filtered array:

Output
[ {name: "Shark", habitat: "Ocean"}, {name: "Whale", habitat: "Ocean"} ]

An array with the two creatures that have a habitat in the “Ocean” is returned.

Conclusion

In this article, you learned about the filter() Array method.

For more details, consult the MDN Reference on filter().

Filter is only one of several iteration methods on Arrays in JavaScript, read How To Use Array Iteration Methods in JavaScript to learn about the other methods like map() and reduce().


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
Leave a comment