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:
html
Output:
html
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.
<!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>
-1 1 0Example 2:
<!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>
Output:
NaN NaN 0 -1 1Reference:https://devdocs.io/d3~5/d3-array#ascending