Open In App

ES6 | Array filter() Method

Last Updated : 28 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 

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

Output :

[ 6, 7, 8, 9, 10 ]

Time complexity: O(n) 

Auxiliary Space: O(1)

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

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

Output :

[ 'watermelon', 'javascript' ]

Time complexity: O(n) 

Auxiliary Space: O(1)

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

javascript
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); 

Output:

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

Time complexity: O(n) 

Auxiliary Space: O(1)


Next Article

Similar Reads