How to implement a filter() for Objects in JavaScript ?
In this article, we will learn how to implement a filter() for Objects in JavaScript. In JavaScript, the filter() method is a built-in function for the array, not for the object. The filter() method outputs all the element of an array that pass a specific test or satisfies a specific function. The return type of the filter() method is an array that consists of all the elements for which the function callback returns true. But for the object, we have to build a custom filter() method.
Below are the methods for implementing filter() for Objects in JavaScript:
In this approach, we are using the filter() method for filtering out the objects and using a loop for printing the multiple results.
Example: The example returns IT department employees with the help of the filter() method.
javascript
let employees = [
{ name: "Tony Stark" , department: "IT" },
{ name: "Peter Parker" , department: "Pizza Delivery" },
{ name: "Bruce Wayne" , department: "IT" },
{ name: "Clark Kent" , department: "Editing" }
];
let output =
employees.filter(employee => employee.department == "IT" );
for (let i = 0; i < output.length; i++) {
console.log(output[i].name)
};
|
Output
Tony Stark
Bruce Wayne
In this approach, we will create a custom built-in function for filtering the object.
Example: This example shows the implementation of the above-explained approach.
Javascript
let employees = [
{ name: "Tony Stark" , id: 1, department: "IT" },
{ name: "Peter Parker" , id: 2, department: "Pizza Delivery" },
{ name: "Bruce Wayne" , id: 3, department: "IT" },
{ name: "Clark Kent" , id: 4, department: "Editing" }
];
Object.filter = (obj, predicate) =>
Object.fromEntries(Object.entries(obj).
filter(([key, value]) =>
predicate(value)));
let filtered =
Object.filter(employees, employee =>
employee.department === "IT" );
console.log(filtered);
|
Output
{
'0': { name: 'Tony Stark', id: 1, department: 'IT' },
'2': { name: 'Bruce Wayne', id: 3, department: 'IT' }
}
Last Updated :
13 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...