1

My data is all in one long form CSV file and I want the user to be able to choose which country's data they would like to have visualized. In order to do that, I am using the filter function in D3.js. When they choose a country as input, the program will filter out all rows that do not match the input in the CountryName column. Then, it would visualized the filtered data.

I was hoping something like this would work.

data = data.filter(function(d) { return d.CountryName === "China"});

Yet when I do this, I get "data.filter is not a function." I have seen d3.js code that successfully uses data.filter... why won't it work here?

Additional Info:

One of the comments asked what data is. Here's what I have for data:

data = d3.csv("econDataLong.csv", function(d) {
    return {
        CountryName: d.CountryName,
        IndicatorName: d.IndicatorName,
        Year: d.Year,
        Value: +d.Value
    } }
);

filtered = data.filter(function(d) { return d.CountryName === "China"});

console.log(filtered);

I have been doing this to see if I can get filter working, but so far no luck.

Dillon J.
  • 93
  • 8
  • 1
    If `data` is an array, that filter has nothing to do with D3, that's just `Array.prototype.filter`. So, please tell us what `data` is. – Gerardo Furtado Jun 30 '20 at 01:43
  • Thank you for the comment, I just added in more info on what data is. – Dillon J. Jun 30 '20 at 02:56
  • 1
    That's the wrong way to do it. That `data` is just the XHR object (v4 or below) or the promise (v5). You have to use a callback (v4 or below) or the `then` method (v5), with `data` or whatever name you want to give it as the argument in the passed function, not `var data = etc...` like you're doing. – Gerardo Furtado Jun 30 '20 at 03:42

1 Answers1

1

Let's look at the docs for d3.csv (https://d3-wiki.readthedocs.io/zh_CN/master/CSV/).They say d3.csv(url[[, accessor], callback]).

You're providing the url and accessor, but no callback. There are a several ways to do what you want, here is one of them. Remember, d3.csv is asynchronous, so the code isn't necessarily executed top to bottom.

data = d3.csv("econDataLong.csv", function(d) {
    return {
        CountryName: d.CountryName,
        IndicatorName: d.IndicatorName,
        Year: d.Year,
        Value: +d.Value
   } 
   filtered = data.filter(function(d) { return d.CountryName === "China"});
   console.log(filtered);
});

Some more examples can be found at http://learnjsdata.com/read_data.html

Karl Galvez
  • 843
  • 6
  • 15