ES6 | Array filter() Method

The Array filter() is an inbuilt method, this method creates a new array with elements that follow or pass the given criteria and condition.
Few Examples have been implemented below for a better understanding of the concept

Syntax:

var newArray = arr.filter(callback(element[, index[, array]])
[, thisArg])

Parameter: This method accepts 2 parameters which was mentioned above and described below:



  • Callback: The function is a predicate, to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments:
    • element: The current element being processed in the array.
    • index(Optional): The index of the current element being processed in the array.
    • array(Optional): The array filter was called upon.
  • thisArg(Optional): Value to use as this when executing the callback.

Example 1: The filter function filters all the numeric values in the array greater than 5

filter_none

edit
close

play_arrow

link
brightness_4
code

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var result = numbers.filter(number => number > 5);
console.log(result);

chevron_right


Output :

[ 6, 7, 8, 9, 10 ]

Example 2: The filter function filters all the words in the array which have length greater than 5

filter_none

edit
close

play_arrow

link
brightness_4
code

var words = ["hi", "hello", "hey", "apple", "watermelon",
             "lemon", "javascript"];
var result = words.filter(word => word.length > 5);
console.log(result);

chevron_right


Output :

[ 'watermelon', 'javascript' ]

Example 3: The filter function filters all invalid id of users from the array.

filter_none

edit
close

play_arrow

link
brightness_4
code

var jsonarr = [
    {
        id: 1,
        name: "joe"
    },
    {
        id: -19,
        name: "john"
    },
    {
        id: 20,
        name: "james"
    },
    {
        id: 25,
        name: "jack"
    },
    {
        id: -10,
        name: "joseph"
    },
    {
        id: "not a number",
        name: "jimmy"
    },
    {
        id: null,
        name: "jeff"
    },
]
  
var result = jsonarr.filter(user => user.id > 0);
  
console.log(result);

chevron_right


Output:

[{"id":1,"name":"joe"},{"id":20,"name":"james"},
{"id":25,"name":"jack"}] 


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.