JavaScript Filter Strings of an Array based on Length

To filter strings of an Array based on length in JavaScript, call Array.filter() method on this String Array, and pass a function as argument that returns true for the specific condition on string length or false otherwise. filter() method returns an array with elements from the original array that returns true for the given callback function.

Examples

In the following script, we take a String Array arr, and filter strings of length 5.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var arr = ['apple', 'banana', 'cherry', 'watermelon', 'mango'];
        var result = arr.filter((n) => n.length == 5)
        document.getElementById('output').innerHTML = 'Resulting Array : ' + result;
    </script>
</body>
</html>

In the following script, we take a String Array arr, and filter strings of length greater than 5.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var arr = ['apple', 'banana', 'cherry', 'watermelon', 'mango'];
        var result = arr.filter((n) => n.length > 5)
        document.getElementById('output').innerHTML = 'Resulting Array : ' + result;
    </script>
</body>
</html>

Reference JavaScript String Length.

Conclusion

In this JavaScript Tutorial, we have learnt how to use Array.filter() method to filter strings of an array based on string length with examples.