Hướng dẫn dùng d3.ascending JavaScript

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The d3.ascending() function in D3.js is a built-in comparator function for the natural order which accepts two parameters and computes their natural order.

    Syntax:

    d3.ascending(x, y)

    Parameters: This function accepts two parameters x, y whose natural order needs to be computed.

    Return Value: The function has the following return values:

    • Returns -1 if the two values are in ascending order.
    • Returns 1 if the two values are in descending order.
    • Returns 0 if the two values are equal
    • Returns NaN if there are no comparable values, i.e. only one or no parameters are passed to the function.

    Below programs illustrate the d3.ascending() function in D3.js.

    Example 1:

    <!DOCTYPE html>

    <html>

    <head>

        <title>D3.js | d3.ascending() function</title>

    </head>

    <body>

        <script>

            // If the two values are in 

            // ascending order

            document.write(d3.ascending(33, 64) + "<br>"); // -1

            // If the two values are in 

            // descending order

            document.write(d3.ascending(42, 24) + "<br>"); // 1

            // If the two values are equal

            document.write(d3.ascending(43, 43) + "<br>"); // 0

        </script>

    </body>

    </html>

    Output:

    -1
    1
    0
    

    Example 2:

    <!DOCTYPE html>

    <html>

    <head>

        <title>D3.js d3.ascending() function</title>

    </head>

    <body>

        <script>

            // If no values are passed

            document.write(d3.ascending() + "<br>"); // NaN

            // If only one value is passed

            document.write(d3.ascending(42) + "<br>"); // NaN

            // If the two values are equal

            document.write(d3.ascending("x", "x") + "<br>"); // 0

            // If the two values are in

            // ascending order

            document.write(d3.ascending("x", "y") + "<br>"); // -1

            // If the two values are in

            // descending order

            document.write(d3.ascending("y", "x") + "<br>"); // 1

        </script>

    </body>

    </html>

    Output:

    NaN
    NaN
    0
    -1
    1
    

    Reference:https://devdocs.io/d3~5/d3-array#ascending