我有一个 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"}];
我的 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));
我的输出是
[{"key":"India","values":4},{"key":"USA","values":1},{"key":"UK","values":3}]
我想要的输出是(按汇总值排序)
[{"key":"India","values":4},{"key":"UK","values":3},{"key":"USA","values":1}]
我该怎么做?我知道以下浏览器默认排序方法也提供了所需的输出。但是只是想弄清楚 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;
})));
最佳答案
D3 提供条件,ascending descending你可以在 sort method 上使用 inside .不用担心,您正在使用 native javascript 方法,并且很好 stability
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));
关于javascript - d3.js 按汇总字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30480981/