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

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) satisfying the specified function.

Syntax:

var 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    var array = 
        [-1, -4, 5, 6, 8, 9, -12, -5, 4, -1];
    var new_array = 
        array.filter(element => element >= 0);
    document.write(
      "<h2>Output\n</h2>", "<h3>", new_array, "</h3>");
</script>

chevron_right


Output:

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



Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
var employees = [
    {name: "Tony Stark", department: "IT"},
    {name: "Peter Parker", department: "Pizza Delivery"},
    {name: "Bruce Wayne", department: "IT"},
    {name: "Clark Kent", department: "Editing"}
];
  
var output =  employees.filter(employee => employee.department == "IT");
for(var i=0;i<output.length;i++){
   document.write("<h2>", output[i].name, "</h2>", "<br/>")
};
</script>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.