Filter An Array of Different Data Types by Array Filter Method


We use arrays to store multiple values in a single variable and retrieve, filter, or remove as per our needs.

Firstly, we can understand in which condition we can use an array; basically, if you have more than one value, like a list of items of the store, or some values like the status of the task such as pending, in progress, or completed.

But if you have different types in an array-like string, number, or boolean values and you want to filter them by some type then you can use the array filter method.

The type of operator in JavaScript returns "object" for arrays. Arrays use numbers to access their "elements".

So, let's start with an array of different types.

var arrtest = [];

Firstly, push values of different types to the array and the final result of the array looks like the following.

["One", "Two", false, 3, "THree"]

Now we will apply the filter method to filter the array for specific types.


As you can see we have applied the filter method and pass function which can filter by number and return the array with a specific type.

function filterByNumber(obj) {    
    if (typeof (obj) === 'number') {    
        return true;    
    } else {    
        return false;    

In this function, we use a type to return the matching number in the object.

The final output is.


You can use the filter method and apply a type to filter the specific type. For more information about the type of operands, you can see the documentation here