JavaScript Array Method: filter()

Java Script @ Freshers.in

JavaScript arrays come equipped with a multitude of methods for filtering and manipulating their elements efficiently. Among these methods, filter() stands out as a versatile tool for creating new arrays with elements that satisfy a specified condition. In this article, we’ll delve into the filter() method, examining its syntax, functionality, and usage through comprehensive examples.

Syntax:

The syntax of the filter() method is straightforward:

array.filter(callback(element[, index[, array]])[, thisArg])

Parameters:

  • callback: A function that is called for each element in the array. It should return true to keep the element, or false to discard it. It accepts up to three arguments:
    • element: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array filter() was called upon.
  • thisArg (optional): An optional object to be used as this when executing the callback function.

Return Value:

A new array containing elements that pass the specified condition.

Examples:

Let’s explore the filter() method with detailed examples:

Example 1:

let numbers = [1, 2, 3, 4, 5];
let evens = numbers.filter((num) => num % 2 === 0);
console.log(evens); // Output: [2, 4]

In this example, the filter() method is used to create a new array evens containing only the even numbers from the numbers array.

Example 2:

let students = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 }
];

let adults = students.filter((student) => student.age >= 18);
console.log(adults); 
/* Output: 
[
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 }
]
*/

Here, the filter() method is employed to create a new array adults containing only the objects representing students who are adults (age 18 and above).

Example 3:

let words = ['hello', 'world', 'javascript', 'filter'];
let longWords = words.filter((word) => word.length > 5);
console.log(longWords); // Output: ['javascript', 'filter']

In this example, the filter() method is utilized to create a new array longWords containing only the words with a length greater than 5 characters.

Author: user