How to write if conditions in .attr using d3 js

480 views Asked by At

I have created two if conditions inside the function but it is taking only one if condition and returns that. I need to execute both if conditions at same time or how can we write condition before .attr('x2', d => self.x(0)) using d3 js

function updateLines(select) {
    if(data.filter(d => d.esp != null) || (d => d.esp == 0)){ 
        return select
            .attr('y1', d => self.y(d.esp))
            .attr('y2', d => self.y(d.esp))
            .attr('x1', d => self.x(d.hour)-3)
            .attr('x2', d => self.x(d.hour)+3 + self.x.bandwidth())
    }

    if(data.filter(d => esp == null)){
        return select
            .attr('y1', d => self.y(d.esp))
            .attr('y2', d => self.y(d.esp))
            .attr('x1', d => self.x(0))
            .attr('x2', d => self.x(0))
        }
    }
1

There are 1 answers

1
Cornel Stefanache On

The checking should happen at the .attr level because it will be executed for each element in the selection. You can prepare upfront the data filters and check them in the .attr callbacks:

function updateLines(select) {
  const nonNull = data.filter(d => d.esp !== null || d.esp === 0);


  select
    .attr('y1', d => self.y(d.esp))
    .attr('y2', d => self.y(d.esp))
    .attr('x1', d => nonNull.contains(d) ? self.x(d.hour)-3 : self.x(0))
    .attr('x2', d => nonNull.contains(d) ? self.x(d.hour)+3 + self.x.bandwidth() : self.x(0))
}

assuming that the selection was created with .data(data) where data is the same array of objects that is used in the updateLines function.