JavaScript Array Filter(), Filter Array using Filter() Method

JavaScript Array filter() method is used to filter data of a Array. in this tutorial, you will learn how to use the JavaScript Array filter() method to filter elements in an array. let’s begin

JavaScript Array Filter – Introduction

One of the most common tasks when working with an array is to create a new array that contains a subset of elements of the original array.

Syntax

arrayObject.filter(function(currentValue, index, arr), contextObject)

Parameter Values

currentValueThe parameter holds the value of the elements being processed currently.
indexOptional. The array index of the current element
arrThis parameter is optional, it holds the complete array on which Array.filter is called.
contextObjectThis parameter is optional, it holds the context to be passed as this to be used
while executing the callback function. If the context is passed, it will be used
like this for each invocation of the callback function, otherwise undefined is
used as default.

Return value: This method returns a new array consisting of only those elements that satisfied the condition of the arg_function

JavaScript Array Filter- Example

Suppose you have an array of user objects where each object contains two properties: name and age.

let users = [
    {name: 'A', age: 19},
    {name: 'B', age: 13},
    {name: 'C', age: 20},
    {name: 'D', age: 15},
    {name: 'E', age: 25}
];

To find the user whose age is greater than 18, you need to apply filter like below

let filterdUsers = users.filter(function (e) {
    return e.age >= 18;
});
console.log(filterdUsers);

Output

[
     {name: 'A', age: 19},
     {name: 'C', age: 20},
     {name: 'E', age: 25}
]

In this example, we called the filter() method of the usersarray object and passed into a function that tests each element.

Inside the function, we checked if the ageof the each user in the array is greater than or equal to 18.

If it is the case, the function returns true; Otherwise, it returns false. The filter() method includes only the element in the result array if the element satisfies the test in the function that we pass into.

In ES6, it is even cleaner when you use the arrow function (=>).

let filterdUsers = users.filter(user=> user.age> 18);
console.log(filterdUsers);

Output

[
     {name: 'A', age: 19},
     {name: 'C', age: 20}
     {name: 'E', age: 25}
]

Comments are closed.