Skip to content

JavaScript Filter Array of Objects

  • by

In JavaScript, you can filter an array of objects using the filter() method, which creates a new array with elements that pass a test implemented by a provided function.

const filteredArray = originalArray.filter(callbackFunction);

This method takes a callback function as an argument that is called on each element of the array, and the function’s return value determines whether the element is included in the filtered array or not.

JavaScript Filter Array of Objects Example

Simple example code.

const people = [
  { name: 'John', age: 25 },
  { name: 'Mary', age: 30 },
  { name: 'Bob', age: 20 },
  { name: 'Jane', age: 35 }
];

const filteredPeople = people.filter(person => person.age > 25);

console.log(filteredPeople);

In this example, the callbackFunction checks whether the age property of each element is greater than 25, and returns true if it is. The resulting filteredArray will contain the following two objects:

JavaScript Filter Array of Objects

You can use various comparison operators or complex logic inside the callback function to filter the array according to your needs.

Here’s another example that filters an array of objects based on multiple conditions:

const originalArray = [
  { id: 1, name: 'John', age: 25 },
  { id: 2, name: 'Mary', age: 30 },
  { id: 3, name: 'Bob', age: 20 },
  { id: 4, name: 'Jane', age: 35 }
];

const filteredArray = originalArray.filter(item => item.age > 25 && item.name.startsWith('J'));

Comment if you have any doubts or suggestions on this JS filter topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading