JavaScript – Filter Elements of Specific Datatype from Array

To filter elements from an array, based on the condition that they belong to a specific datatype, call filter() method on this Array, and pass a callback function as argument. This callback function must take an element as argument and return true for specific datatype or false otherwise.

Refer JavaScript Array.filter() method.

Examples

In the following script, we take an Array arr with elements of different datatypes, and filter only strings from this Array.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var arr = ['apple', 25, 'banana', true, 80, null];
        var result = arr.filter((n) => typeof(n) == 'string')
        document.getElementById('output').innerHTML = 'Resulting Array : ' + result;
    </script>
</body>
</html>

In the following script, we take an Array arr with elements of different datatypes, and filter only numbers from this Array.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var arr = ['apple', 25, 'banana', true, 80, null];
        var result = arr.filter((n) => typeof(n) == 'number')
        document.getElementById('output').innerHTML = 'Resulting Array : ' + result;
    </script>
</body>
</html>

Reference – JavaScript typeof.

Conclusion

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