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 need.
Firstly, we can understand in which condition we can use array; basically, if you have more than one value, like a list of items of store, or some values like status of 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 typeof operator in JavaScript returns “object” for arrays. Arrays use numbers to access its “elements”.
So, lets start with an array of different types:
  1. var arrtest = [];
  2. arrtest.push(“One”);
  3. arrtest.push(“Two”);
  4. arrtest.push(false);
  5. arrtest.push(3);
  6. arrtest.push(“THree”);

Firstly, push values of different types to array and the final result of array look like the following:

  1. [“One”“Two”false, 3, “THree”]
Now we will apply the filter method to filter the array for specific type.
  1. arrtest.filter(filterByNumber);
As you can see we have applied filter method and pass function which can filter by number and return the array with specific type.
  1. function filterByNumber(obj) {
  2.     if (typeof (obj) === ‘number’) {
  3.         return true;
  4.     } else {
  5.         return false;
  6.     }
  7. }
In this function we use typeof to return the matching number in the object.
The final output is:
  1. [3]

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

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s