Filter an Array of Objects based on a property - JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Filter an Array of Objects based on a property - JavaScript #

To filter an array of objects based on a property:

  1. Call the Array.filter() method on the array.
  2. On each iteration, check if the object's property points to the specific value.
  3. The Array.filter method will return an array with all objects that satisfy the condition.
index.js
const people = [ {name: 'Tom', age: 30}, {name: 'John', age: 40}, {name: 'Dillon', age: 30}, ]; const results = people.filter(obj => { return obj.age === 30; }); // 👇️ [{name: 'Tom', age: 30}, {name: 'Dillon', age: 30}] console.log(results);

The function we passed to the Array.filter method gets called with each element in the array.

On each iteration, we check if the object has an age property with a value of 30. If it does, the object gets added to the new array.

If the condition is never met, the Array.filter function returns an empty array.

You can use the array's length to check if there is at least one object that satisfied the condition.

index.js
if (results.length > 0) { // 👉️ the condition was satisfied at least once }

If you only need to filter for a single object that satisfies a condition, use the Array.find() method.

To filter an array of objects based on a property:

  1. Use the Array.find() method to iterate over the array.
  2. On each iteration, check if the object's property points to the specific value.
  3. The find() method will return the first object that satisfies the condition.
index.js
const people = [ {name: 'Tom', age: 30}, {name: 'John', age: 40}, {name: 'Dillon', age: 30}, ]; const person = people.find(object => { return object.age === 30; }); // 👉️ {name: 'Tom', age: 30} console.log(person); if (person !== undefined) { // 👉️ the condition was satisfied }

The function we passed to Array.find gets called with each element in the array until it returns a truthy value or iterates over the entire array.

Once the callback function returns a truthy value, the corresponding array element is returned from Array.find.

If the callback function never returns a truthy value, then Array.find returns undefined.

Even though there are multiple objects in the array that have the age property with a value of 30, only the first object is returned before the Array.find method short-circuits.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.