How to use reduce() Method In Javascript
Another approach to filter an object array based on attributes is by using the reduce() method. This method can be useful if you want to accumulate filtered elements into a new array while also performing additional operations, such as counting invalid entries or transforming the data simultaneously.
Example: In this example, we’ll use reduce() to filter an array of products based on their price and availability, while also counting the number of unavailable products.
let products = [
{ name: 'Laptop', price: 800, available: true },
{ name: 'Phone', price: 600, available: false },
{ name: 'Tablet', price: 300, available: true },
{ name: 'Monitor', price: 200, available: false },
{ name: 'Keyboard', price: 100, available: true }
];
let unavailableCount = 0;
let availableProducts = products.reduce((acc, product) => {
if (product.available && product.price <= 500) {
acc.push(product);
} else {
unavailableCount++;
}
return acc;
}, []);
console.log('Filtered Products: \n', availableProducts);
console.log('Number of Unavailable Products = ', unavailableCount);
Output
Filtered Products: [ { name: 'Tablet', price: 300, available: true }, { name: 'Keyboard', price: 100, available: true } ] Number of Unavailable Products = 3
How to filter object array based on attributes?
Filtering an object array based on attributes involves selecting objects that meet specific criteria. This is achieved by examining each object’s attributes and retaining only those objects that satisfy the specified conditions, resulting in a subset of the original array.
Here are some common approaches:
Table of Content
- Using filter() method
- Using reduce() Method