简体   繁体   中英

D3 json sorts data

I'm reading a json file with the form below using

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 . 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.

For instance, if you wish to arrange it in ascending order based on the total property,

 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.json('file.json',function(error, data){
  const res = data.sort((a, b) => a.total - b.total);
  // render graph
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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