It's a very common requirement that we want to filter an array of objects in JavaScript by a specific key or property value. That's why, JavaScript has a filter()
method for arrays.
This method returns a new array with those objects that meet a certain condition.
Filter an Array of Objects By a Property
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 },
{ name: 'David', age: 35 },
]
const filtered = people.filter((person) => person.age >= 30)
console.log(filtered)
// Output: [{ name: 'Bob', age: 30 }, { name: 'David', age: 35 }]
I have a people
array with 4 objects. Each object has name
and age
properties.
I want to get the people whose age is 30 or above. I can get those people by using the filter()
method.
I am calling the filter method on the people
array and returning true
if the person.age
property is equal to 30 or greater.
If the age is equal to 30 or greater, it will be added to the filtered array.
Finally, I am getting an array with 2 objects where the age property value is equal to or greater than 30.
Filter an Array of Objects With Multiple Conditions
You can use the filter()
method to filter out an array of objects with multiple conditions i.e. by checking each object against multiple criteria.
const products = [
{ name: 'Chair', price: 50, category: 'Furniture' },
{ name: 'Table', price: 140, category: 'Furniture' },
{ name: 'Lamp', price: 30, category: 'Lighting' },
{ name: 'Desk', price: 200, category: 'Furniture' },
{ name: 'Mirror', price: 80, category: 'Decor' },
]
const filtered = products.filter((product) => {
const priceCondition = product.price >= 50 && product.price <= 150
const categoryCondition = product.category === 'Furniture'
return priceCondition && categoryCondition
})
console.log(filtered)
// Output: [{ name: 'Chair', price: 50, category: 'Furniture' }, { name: 'Table', price: 140, category: 'Furniture' }]
Here, I am filtering the products
array by checking if the product's price is within the specified range and if the product's category matches the desired category.
In this case, I am checking if the product's price is between 50 to 150 and the product's category is equal to "Furniture".
I am getting an array with 2 products that match both of those conditions.