The bisectRight() function is a built-in function in D3.js which accepts a value as one of its parameters and returns the index to insert the element in an array passed as another parameter to maintain a sorted order in a specified range or in the whole array.
The function considers the whole array while finding the index by default unless a range is specified by passing start and end as parameters to the function.
The function binary searches value and checks if it already exists in the range. If found, it is inserted to the right of that element.
Syntax:
html
Output:
html
Output:
html
d3.bisectRight(array, value, start, end)Parameters: This function accepts four parameters mentioned above and described below:
- array: This mandatory parameter contains an array of elements.
- value: This is also a mandatory parameter which contains the value to be inserted in the array.
- start: This is an optional parameter which specifies the starting index of the range.
- end: This is an optional parameter which specifies the last index of the range.
<!DOCTYPE html>
<html>
<head>
<title>D3.js d3.bisectRight() Function</title>
<script src='https://d3js.org/d3.v4.min.js'></script>
</head>
<body>
<script>
var array = [42, 43, 53, 61, 71, 87, 91];
var value1 = 63;
var pos = d3.bisectRight(array, value1);
document.write(value1 + " needs to be inserted at "
+ pos + "<br>");
var value2 = 80;
var pos2 = d3.bisectRight(array, value2);
document.write(value2 + " needs to be inserted at "
+ pos2);
</script>
</body>
</html>
63 needs to be inserted at 4 80 needs to be inserted at 5Example 2: This program illustrate the use of d3.bisectRight() passing all four parameters to the function.
<!DOCTYPE html>
<html>
<head>
<title>D3.js d3.bisectRight() Function</title>
<script src='https://d3js.org/d3.v4.min.js'></script>
</head>
<body>
<script>
var array = [42, 34, 27, 53, 61, 71, 33, 51, 87, 91];
var value1 = 63;
var pos = d3.bisectRight(array, value1, 2, 5);
document.write(value1 + " needs to be inserted at "
+ pos + "<br>");
var pos2 = d3.bisectRight(array, value1, 6, 9);
document.write(value1 + " needs to be inserted at "
+ pos2);
</script>
</body>
</html>
63 needs to be inserted at 5 63 needs to be inserted at 8Example 3: This program illustrate the difference between d3.bisectRight() and d3.bisectLeft() functions.
<!DOCTYPE html>
<html>
<head>
<title>
Difference between d3.bisectRight()
and d3.bisectLeft() functions
</title>
<script src='https://d3js.org/d3.v4.min.js'></script>
</head>
<body>
<script>
var array = [42, 54, 59, 63, 71, 81, 91];
var value = 63;
var pos = d3.bisectLeft(array, value);
document.write(value + " needs to be inserted at "
+ pos + "<br>");
var pos2 = d3.bisectRight(array, value);
document.write(value + " needs to be inserted at "
+ pos2);
</script>
</body>
</html>
Output:
63 needs to be inserted at 3 63 needs to be inserted at 4Reference:https://devdocs.io/d3~5/d3-array#bisectRight