JavaScript Array filter() Method

JavaScript Array filter() method is used to create a new array filled with all elements that pass the test implemented by the provided function. This method does not execute the function for empty elements and does not change the original array.

Syntax

array.filter(callback(element, index, arr), thisValue)

Parameters

callback(required): It is the test function to execute on each array element; returns true if the element passes the test, else false.

  1. element(required): It is the current element.
  2. index(optional): It is the current index.
  3. arr(optional): It is the original array.

thisValue(optional): It specifies this value inside the callback function.

Return value

It returns an array of elements that pass the test.

Visual RepresentationVisual Representation of JavaScript Array filter() Method

Example 1: How to Use Array filter() method

let numbers = [10, 22, 31, 54, 77];
newArray = numbers.filter(isGreaterThan);
console.log(newArray);

function isGreaterThan(value) {
 return value > 50;
}

Output

[ 54, 77 ]

Example 2: Using Arrow functionVisual Representation of Using Arrow() with filter() Method 

let numbers = [10, 22, 31, 54, 77];
let isEven = numbers.filter(numbers => numbers % 2 == 0);
console.log(isEven);

Output

[ 10, 22, 54 ]

Example 3: None of the elements in the array pass the testVisual Representation of None of the elements in the array pass test

let numbers = [10, 22, 31, 54, 77];
let newArray = numbers.filter(numbers => numbers > 100);
console.log(newArray);

Output

[]

In the above example, none of the elements is greater than 100 so it returns an empty array.

Example 4: Filter an array of objects

let products = [
  { name: 'Windows', company: 'Microsoft' },
  { name: 'Mac', company: 'Apple' },
  { name: 'Xbox', company: 'Microsoft' },
  { name: 'IPhone', company: 'Apple' }
];

let digitalGoods = products.filter(function(product) {
   return product.company == 'Microsoft';
});

console.log(digitalGoods);

Output

[
{ name: 'Windows', company: 'Microsoft' },
{ name: 'Xbox', company: 'Microsoft' }
]

Browser compatibility

  • Google Chrome 1 and above
  • Edge 12 and above
  • Firefox 1.5 and above
  • Opera 9.5 and above
  • Safari 1 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.