简体   繁体   English

D3 json 对数据进行排序

[英]D3 json sorts data

I'm reading a json file with the form below using我正在使用以下表格读取 json 文件

d3.json('file.json',function(error,data){
    console.log(data);
});

I would expect that the data is stored sequentially (in the order it is stored in the original file) in an array, but if I access the data in my console the array entries are sorted in descending order by their total .我希望数据按顺序存储在一个数组中(按照它存储在原始文件中的顺序),但是如果我在控制台中访问数据,则数组条目按它们的total降序排序。 Why does this happen and how can I avoid it?为什么会发生这种情况,我该如何避免?

[{
    "values":[...],
    "total": 6  
},
{
    "values":[...],
    "total": 45 
},
{
    "values":[...],
    "total": 100    
},
{
    "values":[...],
    "total": 40 
}]

You can try sorting the array using Array.sort() to achieve your desired results.您可以尝试使用Array.sort()对数组进行排序以达到您想要的结果。

For instance, if you wish to arrange it in ascending order based on the total property,例如,如果您希望根据total属性按升序排列,

 const input = [{ "values":[], "total": 6 }, { "values":[], "total": 45 }, { "values":[], "total": 100 }, { "values":[], "total": 40 }]; const res = input.sort((a, b) => a.total - b.total); console.log(res);

This is how you can implement sorting with your d3 code.这就是您可以使用 d3 代码实现排序的方式。

d3.json('file.json',function(error, data){
  const res = data.sort((a, b) => a.total - b.total);
  // render graph
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM