Skip to main content

Command Palette

Search for a command to run...

JavaScript Array: filter() Method

Updated
2 min read
JavaScript Array:  filter() Method
B

A developer documenting his knowledge. #keepLearning #keppGrowing

Sometimes we need to take an array and apply some method(s) to its elements so that we get a new array with modified elements.

Here in this module we will discuss about filter() method of JavaScript array.

The arr.filter() method takes each element from the given array and it will run some set of conditions on it and after execution, it will return a new array. Now while checking the conditions, whichever will return true those Input array elements get pushed in the output array, and whichever will return false that Input array elements will not get pushed in the output array. At the end, we will get a new array with modified values.

Points to remember:
1. filter() does not change the original array.
2. filter() will return a new array.

Syntax

var items = [item1, item2, item3, item4, item5]; <br>
var newArr = items.filter(function(item){
    return condition;
})

in the case of inline arrow function syntax is :

const result = items.filter(x => condition);

Example 1

For example, suppose we are having an array

arr = [105, 923, 30, 23, 500, 1]

Condition: find the number'(s) of array which is greater than 110 by using .filter() method

var arr = [105, 923, 30, 23, 500, 1];
var newArr = arr.filter(function(x){
    return (x>110);
});
console.log(newArr);
// [923, 500]

in another way:

var newArray = arr.filter(x => x>110);
console.log(newArray);
//  [923, 500]

Example 2

var users = [{name: "Michael", id: 1, address:"AUS"}, {name: "John", id: 2, address:"USA"}, {name: "Dwayne", id: 3, address:"NZ"}];

Condition: Find the user's details whose id is 2 from users[]

var users = [
{name: "Michael", id: 1, address:"AUS"}, 
{name: "John", id: 2, address:"USA"},
{name: "Dwayne", id: 3, address:"NZ"}
];
var user = users.filter(function(x){
    return (x.id === 2);
});
console.log(user);
// [{name: "John", id: 2, address: "USA"}]

in other way:

var users = [
{name: "Michael", id: 1, address:"AUS"},
{name: "John", id: 2, address:"USA"},
{name: "Dwayne", id: 3, address:"NZ"}];

var userDetail = users.filter(x => x.id === 2);
console.log(userDetail);
// {name: "John", id: 2, address: "USA"}

More from this blog

simplifying the learning of web development

19 posts

A Web Developer, on a mission to simplify the learning path of web development by sharing good and easy-to-understand content.