score:2

Many ways to solve this. I'd just use a filter with the domain:

var vehiclesLegend = vehiclesLegendWrapper.selectAll('.vehiclesLegendSquare')
  .data(color.domain()) //<-- going to use domain instead
  .enter().append('g')
  .filter(function(d){
     return (d in dataset); //<-- d would be 'truck', 'car', etc.. (pseduo-code, fix for your real dataset)
  })
  .attr('class', 'vehiclesLegendSquare')
  ...
  .style('fill', function(d) {
    return color(d); //<-- back to color
  })

Related Query

More Query from same tag