D3.js中的node.sort()函數用於在給定層次結構數據的每個級別對子級進行排序。比較器函數可用於定義排序的基礎。
用法:
node.sort( compare )
參數:該函數接受如上所述和以下描述的單個參數:
- compare:它是一個函數,它指定應進行排序的基礎。
返回值:此函數返回一個對象。
下麵的示例說明了D3.js中的node.sort()函數:
範例1:
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js">
</script>
</head>
<body>
<script>
// Construct a tree
var tree = {
// Specify the root node
name:"rootNode",
children:[
{ value:1 },
{ value:2 },
{ value:3 },
{ value:4 },
{ value:5 },
{ value:6 },
]
};
var obj = d3.hierarchy(tree);
// Use the sort() function to sort
// the nodes in descending order
var sorted = obj.sum(d => d.value)
.sort((a, b) =>
d3.descending(a.value, b.value));
// Show the sorted output
console.log(
sorted.children.map(
d => ["value", d.value])
);
</script>
</body>
</html>
輸出:
範例2:
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js">
</script>
</head>
<body>
<script>
// Construct a tree
var tree = {
// Specify the root node
name:"rootNode",
children:[
{ value:1 },
{ value:2 },
{ value:3 },
{ value:4 },
{ value:5 },
{ value:6 },
]
};
var obj = d3.hierarchy(tree);
// Use the sort() function to sort
// the nodes in ascending order
var sorted = obj.sum(d => d.value)
.sort((a, b) =>
d3.ascending(a.value, b.value));
// Show the sorted output
console.log(
sorted.children.map(d => ["value", d.value])
)
</script>
</body>
</html>
輸出:
相關用法
- PHP imagecreatetruecolor()用法及代碼示例
- p5.js year()用法及代碼示例
- d3.js d3.utcTuesdays()用法及代碼示例
- PHP ImagickDraw getTextAlignment()用法及代碼示例
- PHP Ds\Sequence last()用法及代碼示例
- PHP array_udiff_uassoc()用法及代碼示例
- PHP geoip_continent_code_by_name()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- PHP GmagickPixel setcolor()用法及代碼示例
- PHP opendir()用法及代碼示例
- PHP cal_to_jd()用法及代碼示例
- d3.js d3.bisectLeft()用法及代碼示例
- PHP stream_get_transports()用法及代碼示例
- PHP Ds\Deque pop()用法及代碼示例
注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 D3.js node.sort() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。