D3.js v5: How can I use filter() to get the data in the selected region of a brushable bar chart

125 Views Asked by At

I was trying to zoom the chart according to the data in the selected region using d3 brush. However, when I tried to use dataselected to receive the filtered data, it just returned an empty array after the selection had been done. I wonder if there is something wrong with my usage of filter() or anything else.

brushed(selection){
  if (selection) {
    console.log(this.data); // Not empty
    let kw0 = this.xScale.invert(selection[0]);
    let kw1 = this.xScale.invert(selection[1]);
    this.xScale2 = d3.scaleLinear()
            .domain([kw0, kw1])
            .range([0, vis.width - vis.margin.right]);
    this.dataselected = this.data.filter(function(d){
            return (kw0 <= this.xScale(d)) && (this.xScale(d) <= kw1);
                });
    console.log(dataselected); // Empty array
  }

The selected bar chart:

enter image description here

1

There are 1 best solutions below

1
wastecvd On

Problem solved. No problem with the usage of filter. I used d.x0 and d.x1 instead of this.xScale(d) and it works.