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

Using filter() method

You can filter an array of objects based on attributes using the filter() method. Provide a callback function that evaluates each object, returning true to keep it or false to discard. The filtered array contains only objects that meet the condition.

Syntax:

let newArray = array.filter(function(item)
{
return conditional_statement;
});

Example 1: We create an array of “students” and call the filter() function on the array to derive the elements from the array that satisfy the given condition.

Javascript
let obj = {
    'Students': [{
        "name": "Raj",
        "Age": "15",
        "RollNumber": "123",
        "Marks": "99",

    }, {
        "name": "Aman",
        "Age": "14",
        "RollNumber": "223",
        "Marks": "69",
    },
    {
        "name": "Vivek",
        "Age": "13",
        "RollNumber": "253",
        "Marks": "89",
    },
    ]
};

let newArray = obj.Students.filter(function (el) {
    return el.Age >= 15 &&
        el.RollNumber <= 200 &&
        el.Marks >= 80;
}
);
console.log(newArray);

Output
[ { name: 'Raj', Age: '15', RollNumber: '123', Marks: '99' } ]

Using reduce() Method

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.

JavaScript
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