Community Post

Data filtering and modelling using JavaScript using build in functions.


Today, JavaScript is getting more and more work to do with the data. The same includes data filtering and modeling. This really necessary with the growing use of SPA frameworks. Applications getting data as JSON and requires some filtering on the data to present it nicely. Note: Will be using some the es-6 features in this post.

Data filtering

We will be using some the JavaScript's well known built in functions. Before we start let's create some sample data.

const rawData  = [1,2,3,40,0, 1012,"one","other", {}, -22, {name:"some"},[],[2,3],'',undefined, null, false, true, NaN];

Our sample data rawData includes false values including NaN, undefined and false.

1. Remove all the false values.

This really simple using built in function Boolean.

let filteredData =  rawData.filter(Boolean); 
[ 1, 2, 3, 40, 1012, "one", "other", {}, -22, { "name": "some" }, [], [ 2, 3 ], true ]

2. Get only numbers out of the sample data.

 let onlyNumbers = rawData.filter(Number);
 [1, 2, 3, 40, 1012, -22, true]

Oh, that was easy. But there is a problem 0 is gone and Boolean true is still there. Is there anyway to get is done correctly? Yes, answer is Number.isFinite.

3. Getting strictly numbers only.

let numbers =  rawData.filter(Number.isFinite);
[1, 2, 3, 40, 0, 1012, -22]

4. Get all arrays from the data.

let allArrays =  rawData.filter(Array.isArray);
[[], [2, 3]] 

For the modeling of data will be doing in part-2 of this series.