2015-09-23 85 views
1

我有一個對象數組,每個對象都有Created字段(類型爲Date)。使用crossfilter.js,我想按月分組這些數據。但它似乎不能正常工作。這裏是代碼:crossfilter.js:按月組數據

生成示例數據,我使用d3's time工具:

var now = new Date(); 
var yearAgo = d3.time.year.offset(now, -1); 
var after6months = d3.time.month.offset(now, 6); 

// data[] will contain one object for each month in the range 
var data = d3.time.month.range(yearAgo, after6months).map(function(date) { 
    return { 
     "Created": date, 
     "Type": 'solid', 
     "State": "Down" 
    }; 
}); 

var cf = crossfilter(data); 
var byDate = cf.dimension(function(d) { return d.Created; }); 

// here I want to group by month and year, eg "October 2015" 
var groupByMonth = byDate.group(function(date) { return d3.time.format("%B %Y")(date); }); 
var grouped = groupByMonth.all(); 

我希望grouped包含每個月份的元素範圍(1.5今年則是18 ),但我得到這個:

"[ { "key": "October 2014", "value": 11 }, { "key": "September 2015", "value": 7 } ]"

Crossfilter下兩組分組的所有記錄,不希望18 我錯了在這裏做什麼?

此代碼生成我需要什麼,但我必須從crossfilter分組得到它:

var desired = d3.nest() 
    .key(function(d) { return d3.time.format("%B %Y")(d.Created)}) 
    .rollup(function(group) { return group.length; }) 
    .entries(data); 

這裏的的jsfiddlehttp://jsfiddle.net/xxjpusa7/5

回答

2

打這裏有一個更新的撥弄它做什麼,我想你希望它能做到。

https://jsfiddle.net/xxjpusa7/4/

var now = new Date(); 
var yearAgo = d3.time.year.offset(now, -1); 
var after6months = d3.time.month.offset(now, 6); 

// data[] will contain one object for each month in the range 
var data = d3.time.month.range(yearAgo, after6months).map(function (date) { 
    return { 
     "Created": date, 
     "Type": 'solid', 
     "State": "Down" 
    }; 
}); 

var cf = crossfilter(data); 
var dateFormat = d3.time.format("%B %Y"); 

var byDate = cf.dimension(function (d) { 
    return dateFormat(d.Created); 
}); 

// Groups using the identity function 
var groupByMonth = byDate.group(); 

var grouped = groupByMonth.all(); 

d3.select("div").text(JSON.stringify(grouped)); 

基本上尺寸被格式化的日期更改爲索引數據。並且byDate.group();負責計算維度中的唯一索引(在本例中爲month year)。它可以將組視爲map-reduce而不是實際的分組。

+0

謝謝。有用。但我也需要通過'Created'過濾數據集,也就是說我需要維度來根據實際日期進行索引? – eagor

+0

@eagor然後你可以使用另一個維度,我不是100%確定這是唯一的(或最好的)方式,但它確實看起來更簡單。 –

+0

是的,就我所知,使用另一個維度並在該維度上過濾將是這種情況下的方法。 –