Skip to content
Related Articles

Related Articles

D3.js node.sort() Function
  • Last Updated : 31 Aug, 2020

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:

  • compare: It is a function that specifies the basis on which sorting should be done.

Return Value: This function returns an object.

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



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

Output:

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

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :