d3.js 按汇总字段排序

Sri*_*ran 3 javascript d3.js

我有一个 JSON 数据,我想按字段分组,然后按计数排序。

var data = [{"Name":"Ravi","Country":"India"},
            {"Name":"Alex","Country":"USA"},
            {"Name":"Stew","Country":"UK"},
            {"Name":"Mary","Country":"India"},
            {"Name":"Raju","Country":"India"},
            {"Name":"Bill","Country":"UK"},
            {"Name":"Elisa","Country":"UK"},
            {"Name":"Sharma","Country":"India"}];
Run Code Online (Sandbox Code Playgroud)

我的 d3.js 查询如下

var countryCount = d3.nest()
                    .key(function(d) { return d.Country; })
                    .rollup(function(a){return a.length;})
                    .entries(data);
console.log(JSON.stringify(countryCount));
Run Code Online (Sandbox Code Playgroud)

我的输出是

[{"key":"India","values":4},{"key":"USA","values":1},{"key":"UK","values":3}]
Run Code Online (Sandbox Code Playgroud)

我想要的输出是(按汇总值排序)

[{"key":"India","values":4},{"key":"UK","values":3},{"key":"USA","values":1}]
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我知道以下浏览器默认排序方法也提供了所需的输出。但只是想弄清楚 d3.js 是否提供任何内置方法来实现这一点

console.log(JSON.stringify(countryCount.sort(function (a, b){
    if (a.values > b.values) {return -1;} 
    else if (a.values < b.values) { return 1;} 
    else  return 0;
})));
Run Code Online (Sandbox Code Playgroud)

Raú*_*tín 5

D3 提供条件,升序 降序,您可以在sort 方法中使用 inside 。不用担心您正在使用具有良好稳定性的本机javascript方法

var countryCount = d3.nest()
                    .key(function(d) { return d.Country; })
                    .rollup(function(a){return a.length;})
                    .entries(data)
                    .sort(function(a, b){ return d3.ascending(a.values, b.values); })

console.log(JSON.stringify(countryCount));
Run Code Online (Sandbox Code Playgroud)

  • 尽管@SriramajeyamSugumaran 接受了这个答案作为正确答案,但它没有显示 d3 进行排序的方式。您应用的`sort()` 方法不是d3 的API 之一,而是OP 已经提到的`Array.prototype.sort()`。您只是在使用 `d3.ascending()`,通过查看您链接到的文档/实现,它在逻辑上等同于上述问题中的比较函数。没有根据请求对叶节点进行排序的内置函数。 (2认同)