JavaScript – Filter Array

JavaScript Array filter() method is used to filter the elements of this Array using the callback function. Array.filter() method returns a new array with elements of the original array that returned true for the callback function.

Syntax

The syntax to call filter() method on an array x with a callback function callback is

</>
Copy
x.filter(callback)

Examples

In the following example, we take an array of numbers, and filter only even numbers using Array.filter() method.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var arr = [2, 5, 8, 11, 13, 16];
        var result = arr.filter((element) => element % 2 == 0);
        document.getElementById('output').innerHTML = result;
    </script>
</body>
</html>

In the following example, we filter strings that start with character b using Array.filter() method.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var arr = ['apple', 'banana', 'mango', 'berry'];
        var result = arr.filter((element)=> element.startsWith('b'));
        document.getElementById('output').innerHTML = result;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we have learnt how to use filter() method on an Array to filter the elements of an Array based on a function.