You can use the filter() method. The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Here's an example of how to filter an array of objects by specific attributes:
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 25 },
{ id: 4, name: 'David', age: 35 }
];
// Filter users by age = 25
const filteredUsers = users.filter(user => user.age === 25);
console.log(filteredUsers);
In this example, the array users is filtered by the age attribute, and only those with age === 25 are included in the filteredUsers array.
You can filter by multiple attributes by combining conditions:
// Filter users by age = 25 and name starts with 'A'
const filteredUsers = users.filter(user => user.age === 25 && user.name.startsWith('A'));
console.log(filteredUsers);
This will return all users who are 25 years old and have a name starting with 'A'.