How to use filter() method In Javascript
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.
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' } ]
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