'D3: What is a Bisector?

I'm looking into making charts with D3, and stumbled upon the d3.bisector. However, I don't understand what it is or does from the documentation.

Almost all examples that I find in the web use a Date array, similar to the example in the official documentation:

var data = [
  {date: new Date(2011,  1, 1), value: 0.5},
  {date: new Date(2011,  2, 1), value: 0.6},
  {date: new Date(2011,  3, 1), value: 0.7},
  {date: new Date(2011,  4, 1), value: 0.8}
];

var bisect = d3.bisector(function(d) { return d.date; }).right;

So what does the bisector do, besides picking the date object from the array elements? What does the *.right return?

And is it of any use if I have a simple 1-dimensional array, like var data = [3, 6, 2, 7, 5, 4, 8]?

Thanks for enlightening me.



Solution 1:[1]

From the documentation (that you've linked to):

Locate the insertion point for x in array to maintain sorted order.

That's what it does. It tells you where a new element should be inserted to still have a sorted array after that. The array can be any kind of structure, which is why there's an accessor function that allows you to "decompose" this structure for the purposes of searching.

The difference between left and right bisects is where the insertion point is (to the left or right of the closest element) -- whether the array is sorted ascending or descending.

One use case for the bisectors is where you want to highlight the closest data point when moving the mouse over a graph, see e.g. this example.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lars Kotthoff