Filtering array in JavasScript

Parvez Alam
2 min readFeb 25, 2023

The filter() method in JavaScript allows you to filter an existing array based on a specific condition by passing a callback function as an argument. The filtered array will only include the elements that meet the specified condition.

The filter() method does not execute the function for empty elements and does not change the original array.

Syntax:

array.filter(function(currentValue, index, arr), thisValue)

The parameters:

  • callback(required): This is a callback method that holds the function to be called for each element of the array.
  • element(required): This is a value of the elements being processed currently.
  • index(optional): This param is used for the index of the current element in the array starting from 0.
  • arr(optional): It contains the complete array on which Array.every is called.
  • thisValue(optional):: it holds the context to be passed as this is to be used while executing the callback function.

Advertisements

Filtering array in Javascript

Let’s demonstrate some examples of filter arrays. I am creating the below script to select only the even numbers from an array of numbers:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const even_numbers = numbers.filter(number => number % 2 === 0); console.log(evenNumbers);

in the above code :

  • We have initialized the array.
  • Applied filter() methods, that create a new array called “even_numbers” by testing each element in the “numbers” array using the callback function that checks whether the number is even.
  • The result is a new array containing only the even numbers.

Output:

[2, 4, 6, 8, 10]

You can also apply any conditional operators :

const fruits = ["apple", "banana", "orange", "kiwi", "pear"]; const shortFruits = fruits.filter(fruit => fruit.length < 5); console.log(shortFruits);

in the above code, the callback function checks whether the length of the string is less than 5. The result is a new array containing only the fruits with a length less than 5.

Output:

["kiwi", "pear"]

Conclusions:

The filter() method is a powerful tool in JavaScript for selecting elements from an array based on certain criteria.

Originally published at https://www.js-tutorials.com on February 25, 2023.

--

--

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/