当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


d3.js nest.sortKeys()用法及代码示例


D3.js是使用JavaScript构建的库,尤其用于数据可视化。 nest.sortKeys()函数用于按特定顺序(即升序或降序)对键进行排序。

用法:

nest.sortkeys( comparatorFunction )

参数:该函数接受单个参数比较器函数,该函数用于指定如何对键进行排序。如果没有为当前键指定比较器函数,则未定义返回键的顺序。

返回值:它根据比较器函数返回排序的键(升/降)。

以下示例程序旨在说明D3.js中的nest.sortKeys()函数。



范例1:

HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" path1tent= 
        "width=device-width, initial-scale=1.0"> 
  
    <script src="https://d3js.org/d3.v4.min.js"> 
    </script> 
  
    <title> 
        D3.js nest.sortKeys() Function 
    </title> 
</head> 
  
<body> 
    <script> 
          
        // Dataset 
        var cars = [ 
            { name:"car1", manufactured:"1950", model:"s51" }, 
            { name:"car1", manufactured:"1952", model:"s51" }, 
            { name:"car1", manufactured:"1951", model:"s50" }, 
            { name:"car1", manufactured:"1953", model:"s52" }, 
            { name:"car1", manufactured:"1953", model:"s50" }, 
            { name:"car1", manufactured:"1950", model:"s52" }, 
        ]; 
  
        var groupedData = d3.nest() 
            .key(function (d) { return d.manufactured; }) 
  
            // sorting keys in ascending order 
            .sortKeys(d3.ascending) 
            .entries(cars); 
        console.log("ArrayData:", groupedData); 
    </script> 
</body> 
  
</html>


输出:

键按升序排列

范例2:

HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" path1tent= 
        "width=device-width, initial-scale=1.0"> 
  
    <script src="https://d3js.org/d3.v4.min.js"> 
    </script> 
  
    <title> 
        D3.js nest.sortKeys() Function 
    </title> 
</head> 
  
<body> 
    <script> 
        var cars = [ 
            { name:"car1", manufactured:"1950", model:"s51" }, 
            { name:"car1", manufactured:"1952", model:"s51" }, 
            { name:"car1", manufactured:"1951", model:"s50" }, 
            { name:"car1", manufactured:"1953", model:"s52" }, 
            { name:"car1", manufactured:"1953", model:"s50" }, 
            { name:"car1", manufactured:"1950", model:"s52" }, 
        ]; 
        var groupedData = d3.nest() 
            .key(function (d) { return d.manufactured; }) 
  
            // Sorting keys in descending order 
            .sortKeys(d3.descending) 
            .entries(cars); 
        console.log("ArrayData:", groupedData); 
    </script> 
</body> 
  
</html>


输出:

键按降序排列




相关用法


注:本文由纯净天空筛选整理自tarun007大神的英文原创作品 D3.js nest.sortKeys() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。