我有一个 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)
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)
| 归档时间: |
|
| 查看次数: |
5413 次 |
| 最近记录: |