• JavaScript Video Tutorials

JavaScript - Array filter() Method



In JavaScript, the Array.filter() method is used to create a new array with elements that pass a certain condition. It takes a callback function as its argument which is executed for each and every element in the array. If the callback function returns true, the element is added to the new array or else it is filtered out.

This method does not change or modify the original array. Also, it does not execute the callback function for empty elements.

Syntax

Following is the syntax of JavaScript Array filter() method −

array.filter(callbackFn (element, index, array), thisArg);

Parameters

This method accepts two parameters. The same is described below −

  • callbackfn − This is a callback function that will be called once for each element in the array. It further takes three arguments:
    • element − The current element being processed in the array.
    • index − The index of the current element being processed.
    • array − The array of the current element.
  • thisArg (optional)− It specifies a value passed to the function to be used as its this value.

Return value

This method returns a new array containing the elements for which the callback function returned true.

Examples

Example 1

In the following example, the provided callback function checks each element in the “numbers” array and returns a new array, “result”, containing all the elements that are greater than 30.

<html>
<body>
   <script>
      const numbers = [10, 20, 30, 40, 50];

      const result = numbers.filter(function (number) {
         return number > 30;
      });
      document.write(result);
   </script>
</body>
</html>

Output

40,50

Example 2

Here, the provided callback function checks if each element in the array includes the letter ‘a’ −

<html>
<body>
   <script>
      const animals = ['Lion', 'Cheetah', 'Tiger', 'Elephant', 'Dinosaur'];

      const result = animals.filter(function (element) {
         return element.includes('a');
      });
      document.write(result);
   </script>
</body>
</html>

Output

Cheetah,Elephant,Dinosaur

Example 3

In this example, we are checking if each age is greater than or equal to 18 −

<html>
<body>
   <script>
      const ages = [18, 25, 13, 16, 22, 15];

      const result = ages.filter(function (age) {
         return age >= 18;
      });
      document.write(result);
   </script>
</body>
</html>

Output

18,25,22
Advertisements