Open In App

D3.js node.sort() Function

The node.sort() function in D3.js is used to sort the children at each level of the given hierarchical data. The comparator function can be used to define the basis on which the sorting would be done.

Syntax:



node.sort( compare )

Parameters: This function accepts a single parameter as mentioned above and described below:

Return Value: This function returns an object.



Below example illustrates the node.sort() function in D3.js:

Example 1:




<!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>

Output:

Example 2:




<!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>

Output:


Article Tags :