The bisectCenter() method in D3.js is used to return the index of the value closest to the given value in an array of numbers. A subset of the array to be considered can be specified by using the lo and hi parameters.
Syntax:
d3.bisectCenter( array, x, lo, hi )
Parameters: This method accepts four parameters as mentioned above and described below:
- array: It is the array to be used for finding the value.
- x: It is the value to be inserted.
- lo: It defines the lower index of the subset of the array to be considered. It is an optional parameter.
- hi: It defines the higher index of the subset of the array to be considered. It is an optional parameter.
Return value: It returns the index of an array after insertion of the new element.
Note: To execute the below examples you have to install the d3 library. The following command prompt we have to execute the following command.
npm install d3
Example 1: In this example, we can see that by using this method, we are able to find the index of the value which is closest to the values in the array.
Javascript
// Defining d3 contrib variable var d3 = require( 'd3' ); var insert_index = d3.bisectCenter([1, 2, 3, 4, 5], 2); console.log(insert_index); |
Output:
1
Example 2: In this example, we can see that by using this method, we are able to find the index of the value which is closest to the floating values in the array.
Javascript
// Defining d3 contrib variable var d3 = require("d3"); var arr = [0.2918, 0.0157, 0.637, 0.3536, 0.6813]; var insert_index = d3.bisectCenter(arr, 0.5); console.log(insert_index); |
Output:
2