1

I am new to d3 and trying to plot some data in one box for each of four specific states, similar to this page but with states not continents, and a lot more data points. I have a json dataset of more than 42,000 entries supposedly from just those 4 states.

To key by state, I used this:

d3.json("data/business.json",function(json) {
  var data=d3.nest()
    .key(function(d) {return d.state;})
    .sortKeys(d3.ascending)    
    .entries(json);

Then later make one box for each state:

  // One cell for each state
  var g=svg.selectAll("g").data(data).enter()
    .append("g")

(attributes, etc)

Fine, but I soon found that the dataset includes some data from several states I don't want to consider so it was plotting more boxes than I wanted.

I would like a way to exclude the data that isn't from the four states without altering the original data file. What is the best way to go about this?

punstress
  • 1,177
  • 2
  • 14
  • 26

2 Answers2

1

Filter your json:

var keep = ["state1", "state2", "state3", "state4"];
json = json.filter(function(d) { return keep.indexOf(d.state) > -1; });
Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Yep! Can you tell me why the same line doesn't work with json = json.filter(function(d) { return keep.contains(d.state); }); Says not a function. Isn't that valid JS? – punstress Sep 25 '14 at 09:40
  • 1
    @punstress `array.contains()` isn't valid javascript. [Here](http://stackoverflow.com/questions/237104/array-containsobj-in-javascript) is a related SO question. – Baz Sep 25 '14 at 10:07
  • Not sure why I found contains() if it isn't a method though. :/ – punstress Sep 25 '14 at 10:17
0

It's possible to filter the output from d3.nest rather than the original array:

  function trim(nested, f) {
    return nested
        .filter(function (e) {
          return f(e.key)
        })
        .map(function (e) {
          if (e && (typeof e =='object') && Array.isArray(e.values) && ('key' in e)) {
            return { key: e.key, values: trim(e.values, f)}
          }
          else return e
        })
  }

For instance:

  function isNewEngland(st) {
      return ["ME","VT","NH","MA", "CT", "RI"].indexOf(st)>=0 
  }

  data = trim(data, isNewEngland)
prototype
  • 7,249
  • 15
  • 60
  • 94