D3 Nest - 排序值

时间:2017-02-12 18:07:42

标签: javascript d3.js

我正在尝试使用D3.nest()按键和值对数据集进行排序,两者都是根据自定义的数组顺序。密钥排序工作没有问题,但我没有能够对值进行排序。

我的自定义排序数组定义为:

var priority_source_order = ["Biological","Water","Sediment","Eco-Fish"];
var priority_indicator_order = ["Biological Status","Water Quality Index","Phosphorus","Nitrogen","Dissolved Oxygen","Water Clarity","Chlorophyll a","Sediment Quality Index","Sediment Contaminants","Sediment Toxicity","Fish Quality Index"];

.sortKeys方法工作正常,但我无法对值进行排序。这可能是因为有多个键/值对嵌套在"值" D3.nest()创建的密钥,函数不知道需要对哪个密钥进行排序。这是我的代码:

var final_data = d3.nest()
            .key(function(d) { 
                return d[ncca_ce_source];
            })
            .sortKeys(function(a,b) { 
                return priority_source_order.indexOf(a) - priority_source_order.indexOf(b); 
            })
            .sortValues(function(a,b) { 
                return priority_indicator_order.indexOf(a) - priority_indicator_order.indexOf(b); 
            })
            .entries(cond_est_data);

我的数据目前如下:

[
 {
  "key": "Biological",
  "values": [
   {
    "Type": "National",
    "Indicator.Plain.Language": "Benthic Index"
   }
  ]
 },
 {
  "key": "Water",
  "values": [
   {
    "Type": "National",
    "Indicator.Plain.Language": "Chlorophyll a"
   },
   {
    "Type": "National",
    "Indicator.Plain.Language": "Dissolved Oxygen"
   }
  ]
 }
]

有没有人对如何排序" Indicator.Plain.Language"根据priority_indicator_order数组的顺序键?正如您在上面的输出中所看到的那样,"键"生物和水的分类正确。但是," Indicator.Plain.Language"的值不是priority_indicator_order数组定义的顺序。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

通过将.sortValues方法修改为以下内容来解决此问题:

.sortValues(function(a,b) { 
    return priority_indicator_order.indexOf(a[ncca_ce_indic_plain]) - priority_indicator_order.indexOf(b[ncca_ce_indic_plain]); 
})