D3.js | d3.ascending() Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>D3.js | d3.ascending() function</title>
  
    <script src='https://d3js.org/d3.v4.min.js'></script>
</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>

chevron_right


Output:

-1
1
0

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>D3.js d3.ascending() function</title>
  
    <script src='https://d3js.org/d3.v4.min.js'></script>
</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>

chevron_right


Output:

NaN
NaN
0
-1
1

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



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.