Custom Bisectors
D3 allows us to create custom bisector functions that search for items in an array.
We'll cover the following...
We are going to create a custom bisector function. D3 comes with a bisect()
function, but it is only capable of comparing numbers. We need to compare dates. Luckily, D3 comes with a function for creating a custom bisector for searching through an array with non-numeric values. We’re going to continue working on the event handler function.
Creating a custom bisector
Inside the function, we are going to replace the index
variable.
// Tooltipctr.append("rect").style('opacity', 0).attr("width", dimensions.ctrWidth).attr("height", dimensions.ctrHeight).on('touchmove mousemove', function(event) {const mousePos = d3.pointer(event, this)const date = xScale.invert(mousePos[0])// Custom Bisector - left, center, rightconst weatherBisect = d3.bisector(xAccessor).leftconst index = weatherBisect(dataset, date)const weather = dataset[index - 1]console.log(weather)}).on('mouseleave', function(event) {})
It is being set too early because we do not have the custom bisector function defined. We have a variable called weatherBisect
. Its value will be the d3.bisector()
function.
The bisector()
function will allow us to create a custom bisect function. The reason we will create a custom bisector function is because we need to tell D3 how to access the date in our dataset. This function has one argument, which is an accessor function. We are providing it with the ...