Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptD3.js node.sort() Function

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:

  • 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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments