Skip to content Skip to sidebar Skip to footer

D3.bisector On Descending Array

I am creating a simple D3 line chart and am having trouble creating the tooltip with the d3.bisector() function. I am looking for it to go to the Y and X axis for each value. The b

Solution 1:

The documentation on d3.bisector() has you covered (emphasis mine):

Use a comparator rather than an accessor if you want values to be sorted in an order different than natural order, such as in descending rather than ascending order.

The signature of that method allows you to pass in a comparator function which is called with the search value passed as the second argument. You can thus have a bisector for an array in descending order like so:

d3.bisector((d, x) => x - d).left//              ^--- Search value

Have a look at the following working demo:

const yData = [10,9,8,7,6,5,4,3,2,1,0];

const descBisector = d3.bisector((d, x) => x - d).left;
const yIndex = descBisector(yData, 2);

console.log(yIndex);
<scriptsrc="https://d3js.org/d3.v5.js"></script>

Post a Comment for "D3.bisector On Descending Array"