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 function callback returned true. But for the object, we have to build a custom filter() method.
Below are the methods for implementing filter() for Objects in JavaScript:
- Using for loop and filter() Methods
- Using Object.entries() and Object.fromEntries() Method
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 method we will create custom built-in function for filtering the object.
Example:
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' }
}
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Aug, 2023
Like Article
Save Article