Filter an Array of Objects based on a property - JavaScript

avatar

Borislav Hadzhiev

Mon Oct 04 20212 min read

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 passing it a function
  2. The function will be called with each element of the array and should do a conditional check on the property
  3. The Array.filter methods returns an array with all elements that satisfy the condition
index.js
// ๐Ÿ‘‰๏ธ Supported in IE 9-11 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 will get called with each element of the array.

We conditionally check if the object has an age property with a value of 30, if it does then the object is included in the final array.

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

To check if there is at least one object that satisfied the condition, check the array's length:

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 in the array, use the Array.find method .

index.js
// ๐Ÿ‘‰๏ธ Not Supported in IE 6-11 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 all elements.

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 our array that have the age property with a value of 30, only the first object is returned and the Array.find method short circuits.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee