Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to implement a filter() for Objects in JavaScript ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The filter() method basically outputs all the element object 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 element(s)/object(s) for which function callback returned true. 

Syntax:

let newArray = arr.filter(callback(object[, ind[, array]])[, Arg])

Parameters:

  • Callback is a predicate, to test each object of the array. Returns True to keep the object, False otherwise. It takes in three arguments:
  • Object: The current object being processed in the array.
    • ind (Optional): Index of the current object being processed in the array.
    • array (Optional): Array on which filter was called upon.
  • Arg (Optional): Value to use(.this) when executing callback.

Example 1: It is a basic example of using filter() method.

javascript




let array =
    [-1, -4, 5, 6, 8, 9, -12, -5, 4, -1];
let new_array =
    array.filter(element => element >= 0);
console.log("Output: " + new_array);

Output: 

Output: 5,6,8,9,4

 The above example returns all the positive elements in a given array. 

Example 2: The example returns IT department employees with the help of 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
My Personal Notes arrow_drop_up
Last Updated : 18 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials