Skip to content
Related Articles

Related Articles

Improve Article

D3.js bisect() Function

  • Last Updated : 29 Jul, 2020

The bisect() 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 left of that element.

Syntax:

d3.bisect(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.

Return value: The function returns a single integer value denoting the index where value needs to be inserted in the array to maintain sorted order.

The below programs illustrate the use of d3.bisect() function :

Example 1: This program illustrates the use of d3.bisect() passing only the two mandatory parameters.




<!DOCTYPE html> 
<html
    
<head
    <title>D3.js d3.bisect() 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.bisect(array, value1); 
        document.write(value1 + " needs to be inserted at "  
        + pos + "<br>"); 
    
        var value2 = 80; 
        var pos2 = d3.bisect(array, value2); 
        document.write(value2 + " needs to be inserted at "  
        + pos2); 
    </script
</body
    
</html>

Output:

63 needs to be inserted at 4
80 needs to be inserted at 5

Example 2: This program illustrates the use of d3.bisect() passing all four parameters to the function.




<!DOCTYPE html> 
<html
    
<head
    <title>D3.js d3.bisect() 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.bisect(array, value1, 2, 5); 
        document.write(value1 + " needs to be inserted at "  
        + pos + "<br>"); 
    
        var pos2 = d3.bisect(array, value1, 6, 9); 
        document.write(value1 + " needs to be inserted at "  
        + pos2); 
    </script
</body
    
</html>

Output:

63 needs to be inserted at 5
63 needs to be inserted at 8

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :