简体   繁体   中英

How to sort a map-of-maps (hierarchy) with D3.js

I am learning how to handle data through D3.js and D3's hierarchy at the moment but can't get my head around sorting a map of maps structure.

Given the following dataset

continent,country,city,population
Americas,US,Los Angeles,232324
Americas,US,New-York,120303
Asia,INDIA,Delhi,4533003
Asia,CHINA,Beijing,30234
Europe,FRANCE,Paris,1002000
Europe,GERMANY,Berlin,394223

I am generating a map of maps over the 3 first tabs, apply a hierarchy and order by (1) continent (DESCENDING)

let mappedData = d3.group(csvData, d => d.continent, d => d.country, d => d.city);
let d3hierarchy = d3.hierarchy(mappedData);
d3hierarchy.sort((a, b) => d3.descending(a.data[0], b.data[0]))

d3hierarchy looks like this and children are sorted by decsending order: d3 层次结构

I am trying to sort the hierarchy :

  1. by continent (DESC) - already done
  2. by country (ASC)
  3. by city (DESC)

After scratching my head for few hours, I can't really get around how to sort the sub-sequent sorts (country and city). What would be your best approach?

I used mostly the following D3 ressources:

Since d3.sort :

sorts the children of this node, if any, and each of this node's descendants' children https://github.com/d3/d3-hierarchy#node_sort

In order to sort each level independently, one has to compare and sort nodes on equal levels like the following example:

d3hierarchy.sort(function (a, b) 
{
      if (a.height == 3 && b.height == 3) {
        return d3.ascending(a.data[0], b.data[0])
      }

      if (a.height == 2 && b.height == 2) {
        return d3.descending(a.data[0], b.data[0])
      }

      if (a.height == 1 && b.height == 1) {
        return d3.ascending(a.data[0], b.data[0])
      }

      // getting to the leaf
      if (a.height == 0 && b.height == 0) {
        return d3.descending(a.data.Population, b.data.Population)
      }
});

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