A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript-array-filter-method/ below:

JavaScript Array filter() Method - GeeksforGeeks

JavaScript Array filter() Method

Last Updated : 10 Jan, 2025

The filter() method creates a new array containing elements that satisfy a specified condition. This method skips empty elements and does not change the original array.

Create a new array consisting of only those elements that satisfy the condition checked by canVote() function.

JavaScript
// JavaScript to illustrate findIndex() method
function canVote(age) {
    return age >= 18;
}

let filtered = [24, 33, 16, 40].filter(canVote);
console.log(filtered);

Syntax

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

Parameters: This method accepts five parameters as mentioned above and described below: 

Parameter Description callback The function is to be called for each element of the array. element The value of the element currently being processed. index (Optional) The index of the current element in the array, starting from 0. arr (Optional) The complete array on which Array.every is called. thisValue (Optional) The context to be passed as this to be used while executing the callback function. If not provided, undefined is used as the default context.

Return value: It returns an array of elements that pass the test and an empty array if no elements pass the test. 

Example 1: Creating a new array consisting of only those elements that satisfy the condition checked by isPositive() function.

JavaScript
function isPositive(value) {
    return value > 0;
}

let filtered = [112, 52, 0, -1, 944].filter(isPositive);
console.log(filtered);

Example 2: Creating a new array consisting of only those elements that satisfy the condition checked by isEven() function. 

JavaScript
function isEven(value) {
    return value % 2 == 0;
}

let filtered = [11, 98, 31, 23, 944].filter(isEven);
console.log(filtered);

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4