I want to select some data out of a CSV file before i load it with javascript (with the d3 library).
This is how i load the CSV:
d3.csv("data.csv", function(csv) {
vis.datum(csv).call(chart);
});
And this is a sample of the CSV file:
Class,Age,Sex,Survived
First Class,Adult,Male,Survived
First Class,Adult,Male,Survived
First Class,Adult,Male,Survived
First Class,Adult,Male,Survived
First Class,Adult,Male,Survived
First Class,Adult,Female,Survived
First Class,Adult,Female,Survived
First Class,Adult,Female,Survived
Second Class,Adult,Male,Perished
Second Class,Adult,Male,Perished
Second Class,Adult,Male,Perished
Third Class,Adult,Male,Survived
Third Class,Adult,Male,Survived
Third Class,Adult,Male,Survived
Third Class,Adult,Male,Survived
Third Class,Adult,Male,Perished
Third Class,Adult,Male,Perished
Crew,Adult,Male,Perished
Crew,Adult,Male,Perished
Crew,Adult,Female,Survived
Crew,Adult,Female,Survived
For example i want only to select the Second Class and First Class rows before i load it with d3.csv.
i know i can just delete the other rows in the CSV, but i want to make a function so that the user can select what categories he want to use. I hope that makes some sense.
The quick answer is, use
.filter()to select the rows you want, e.g.:This is easy if you, the coder, are choosing the filters. If you need this to be chosen by user interaction, however, you’re going to need to build out a more complex function. Assuming that you have saved the user choices in an object called
filters, with keys corresponding to your rows, one option might look like:(You don’t have to do this with
.reduce(), but I like how clean it is.)If, as is probably the case, you don’t want to do this filtering at load time, but instead filter dynamically depending on user input, you can still use the filter function, but you’ll want to store
csvin memory somewhere and filter it on the fly, perhaps in anupdate()function triggered by user interactions.