d3.bisector on descending array

前端 未结 1 1515
甜味超标
甜味超标 2021-01-14 06:04

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 f

相关标签:
1条回答
  • 2021-01-14 06:37

    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);
    <script src="https://d3js.org/d3.v5.js"></script>

    0 讨论(0)
提交回复
热议问题