AlgoDaily

How to Filter an Array of Objects in JS

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Revisiting Arrays

How to Filter an Array of Objects in JS

Before we start discussing this topic, let's do a quick revision of both arrays and objects.

At a very high level, arrays are collections of similar things. A common example you might think of is a six-pack of beer. The entire "thing" - the six-pack itself, is an array. Each individual can of beer is an item in an array.

While an array is used to group similar items, at a very high level, you might say that an object is used to describe a unique thing. The word unique here is used in the sense of "a collection of unique characteristics, grouped toghether based on some rules". In other words, an object is a collection of characteristics of a single thing, while an array is a collection of similar things.

This distinction is sometimes not obvious to a beginner programmer, but it is crucial to understand this at a conceptual level. A six-pack of beer cans might be "emulated" in JavaScript as follows:

const sixPack = [
  "beer can 1",
  "beer can 2",
  "beer can 3",
  "beer can 4",
  "beer can 5",
  "beer can 6",
];

So, I'm emulating a six-pack of beers as an array, where each member of that array is a string literal.

An Array of Objects

This brings me to another important conclusion: an array of objects is to be used when I'm collecting a group of "things" that have a number of unique characteristics. Perhaps a different way to describe this is to say that an array of objects is to be used when I'm representing a group of "things" that are unique enough to merit the use of an object for each array item, instead of using a primitive data structure, such as a string.

A perfect example of using an array of objects is to, for example, group an array of users in an app.

Here's such a group of users, represented as an array of JavaScript objects:

```js
const users = [
  { name: "Anna", email: "ana@ana.com", country: "United States" },
  { name: "Suzan", email: "suzan@suzan.com", country: "United Kingdom" },
  { name: "Barbara", email: "barb@barbara.com", country: "United States" },
];

console.log(users);
```

Filtering

Filtering

This brings me to another insight: I need to use objects as array members when these objects have enough distinct data points to merit the use of an object. Otherwise, as with the example of a six-pack of beers, there's not really much distinction between any two items in that six-pack. Put differently, the reason to filter an array of objects in the first place, is essentially to find a sub-group of objects that share a specific property, which makes them different enough from all the other objects in this collection (array) of objects, to merit a use of a filter.

Now you should understand, at a conceptual level, why you might want to filter objects in an array, which brings me to explaining how you would go about doing it.

There are several built-in array methods that allow you to filter an array of items.

Using the array of users, here's how I might filter them by country:

```js
const users = [
  { name: "Anna", email: "ana@ana.com", country: "United States" },
  { name: "Suzan", email: "suzan@suzan.com", country: "United Kingdom" },
  { name: "Barbara", email: "barb@barbara.com", country: "United States" },
];
const americans = users.filter((person) => person.country == "United States");
const brits = users.filter((person) => person.country == "United Kingdom");
console.log(
  "In our list of users, the following come from the USA:",
  americans
);
console.log(
  "In our list of users, here are those that come from the UK:",
  brits
);
```

Objects Passing the Filter

Before thinking about syntax, picture filter() as a row-by-row test.

Each user object enters the predicate check. If person.country == "United States" is true, that whole object is copied into the new array. If it is false, it is skipped. The original users array stays unchanged.

Objects Passing the Filter

Filter as a Sieve

Before moving into the line-by-line explanation, picture filter() as a yes/no test applied to every object in the array.

Each user object passes through the same condition: country == "United States". Objects that return true are copied into a new array; objects that return false are left out.

Filter as a Sieve

Explanation of Filtering

Explanation

So, what I'm doing here is: I'm passing an arrow function to JavaScript's built-in filter() method on the Array.prototype object. This arrow function accepts a single argument that I can name anything I like (as long as I don't violate syntax rules of JavaScript). I named the argument person, since that's what each array item essentially is. Finally, I return the result of running a comparison between each person object's country property and the value of 'United States'.

The == operator checks for equality of type, and returns the boolean of true if the two values match, and the boolean of false if they do not match. Those person objects that passed the equality comparison - that is, those person objects that had the filter's callback function return the boolean of true after checking for equality between person.country and 'United States' - those person objects got pushed into a new array that gets returned from the filter() method call. Since these return array values do not change the source array in any way - that is, they are "non-destructive" - I had to save them as americans and brits - thus, essentially, splitting my source people array into two distinct subsets based on the country property of the people object.

One Pager Cheat Sheet

One Pager Cheat Sheet

  • Filtering an array of objects in JavaScript requires understanding of the distinction between arrays as a collection of similar items and objects as a collection of unique characteristics of a single thing.
  • Using an array of objects is an ideal way to represent a group of items that have multiple unique characteristics, such as a group of users in an app, represented as JavaScript objects.
  • We can filter an array of objects to find a specific set of members based on a certain property that makes them different from the rest of the array.
  • - filter() keeps objects whose predicate returns true and returns them in a new array.
  • - filter() checks each object, keeps the ones that pass, and returns a new smaller array.
  • We used JavaScript's filter() method to split the source people array into two distinct subsets based on the country property and the value of 'United States'.
Open interactive view →