Crossfiltering of JSON data by the most recent time

333 views Asked by At

Hi i was facing problem with filtering out the most recent data from my data file. I have the following data

var data=
[
{"id":1,"speed":50,time:10:51.30},
{"id":1,"speed":40,time:10:51.40},
{"id":1,"speed":60,time:10:51.50},
{"id":1,"speed":55,time:10:51.55},
{"id":2,"speed":55,time:10:51.50},
{"id":2,"speed":65,time:10:51.58}
]

I want to filter out the data to visualize or show the data with most recent time. So my filtered data should contain the following

var filtereddata=
[
{"id":1,"speed":55,time:10:51.55},
{"id":2,"speed":65,time:10:51.58}
]

How can i get the filtered data from data using crossfilter? I was trying with

var ndx=crossfilter(data);
var dim=ndx.dimension(function(d){return d.time;});
var filter=dim.filter(function(d){d3.max(data,function(d){return d.time;})});

But its not working? How can i do it?

1

There are 1 answers

1
Alp On BEST ANSWER

Problem is that you are looking at the filter object. You need to convert filtered dim to array using either top or bottom.

Please see the code below or better check out Here for the working version.

var data=[
{id:1,speed:50, time: new Date('2011-04-11T11:51:00')},
{id:2,speed:40, time: new Date('2011-04-11T11:51:10')},
{id:3,speed:60, time: new Date('2011-04-11T11:51:20')},
{id:4,speed:51, time: new Date('2011-04-11T11:51:30')},
{id:5,speed:55, time: new Date('2011-04-11T11:51:40')},
{id:6,speed:65, time: new Date('2011-04-11T11:51:50')}];




var ndx = crossfilter(data);
var dataByTime = ndx.dimension(function (d) {
    return d.time;
});

var dataBySpeed = ndx.dimension(function (d) {
    return d.speed;
});

//var speedFilter = dataBySpeed.filter(function (d) {});

var timeFilter = dataByTime.filter(function(d){});

//console.log(speedFilter.filterRange([40, 55]).top(3));
console.log(timeFilter.filterRange([new Date('2011-04-11T11:51:00'), new Date('2011-04-11T11:51:40')]).top(3));

______UPDATE_____

OK I see what you meant. See below for updated code snippet. I also updated solution at jsfiddle

var data=[
{id:1,speed:50, time: new Date('2011-04-11T11:51:00')},
{id:2,speed:40, time: new Date('2011-04-11T11:51:10')},
{id:2,speed:60, time: new Date('2011-04-11T11:51:20')},
{id:3,speed:51, time: new Date('2011-04-11T11:51:30')},
{id:3,speed:55, time: new Date('2011-04-11T11:51:40')},
{id:3,speed:65, time: new Date('2011-04-11T11:51:50')}];

var uniqueVals = new Map();
data.forEach(function(d){ 
    var existingVal = uniqueVals.get(d.id);
    if (existingVal){
        if (existingVal.time < d.time){
            uniqueVals.set(d.id, d);
        }
    } else {
        uniqueVals.set(d.id, d);
    }
    });

var finalData = [];
uniqueVals.forEach(function(d){ finalData.push(d); });
console.log(uniqueVals);