d3.js按汇总字段排序 [英] d3.js sorting by rollup field

查看:388
本文介绍了d3.js按汇总字段排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having a JSON data and i want to group by a field and then sort by the count.

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查询如下

and my d3.js query is the following

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}]




by my desired output is ( sorted by rollup value)

[{"key":"India","values":4},{"key":"UK","values":3},{"key":"USA","values":1}]

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

How can i do this? I know that the following browser default sort method also gives desired output. But just want to clear whether d3.js provides any inbuilt method to achieve this.

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 ,您可以在排序方法。不用担心您正在使用本地JavaScript方法,而且稳定性 p>

D3 provide the condition, ascending descending and you can use inside on sort method. No worries You are using a native javascript method with nice 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));

这篇关于d3.js按汇总字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆