如何从d3.v3.min.js中的nest()中检索键?

时间:2016-09-29 07:11:08

标签: javascript csv d3.js

我正在编写一个代码,根据ID的数量查找前6个活动。 CSV就像: 10000电费单支付 10001水费单支付 10002燃气费单支付 10003电费单支付 10001水费单支付 10001水费单支付

我的代码是:

d3.csv("activities.csv", function(error,data) {
//fetching and storing the activities as key and their individual count as value
countByActivties=  d3.nest()
       .key(function(d) { return d.ACTIVITY; })//.sortKeys(d3.ascending)
      .rollup(function(v) { return v.length; }).sortValues(d3.descending)
      //.sortValues(d3.ascending)
      //.sortValues(function(v, d){ return d3.ascending(d.length); })
      .entries(data);
    console.log(JSON.stringify(countByActivties));

输出如下:

[{"key":"Electricity Bill Payment","values":2},{"key":"Water Bill Payment","values":3},{"key":"Gas Bill Payment","values":1}]

根据计数查找前6个活动(即按计数降序排序)。我试过了getKeys函数,但是没有用。以下是相同的代码段:

 for(i=0;i<6;i++){
        countByActivties.getKeys(function(d){ return d.key;})
    } 

它抛出的错误是:

testchartfunction.html:56 Uncaught TypeError: countByActivties.getKeys is not a function.

我要做的是迭代键值以获取数据。

有人对此有任何想法吗?

1 个答案:

答案 0 :(得分:2)

看起来你只想要数组中的前6个元素,然后得到它的键:

而不是这个

var keys = countByActivties
          .sort(function(a, b){return a.values-b.values})
          .slice(0,6)
          .map(function(d){ return d.key;})

这样做:

carListAdapter = new CarListAdapter(carListSuper,MainActivity.this);

首先排序然后获得6个元素。

然后从6个元素中提取密钥。