Most recent cross-filtering of JSON data
Hi I am facing the problem of filtering 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 the data to visualize or display the data most recently. Therefore 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 filtered data from data using crossfilter? I tried 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 this?
+3
source to share
1 answer
The problem is you are looking at a filter object. You need to convert the filtered dim to an array using top or bottom.
Please see the code below or better check here for a 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 understand what you mean. See below for the updated code snippet. I have also updated the solution in 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);
+2
source to share