score:33

Accepted answer

The quick answer is, use .filter() to select the rows you want, e.g.:

d3.csv("data.csv", function(csv) {
    csv = csv.filter(function(row) {
        return row['Class'] == 'Second Class' || row['Class'] == 'First Class';
    })
    vis.datum(csv).call(chart);
});

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:

// an example filters object
var filters = {
    'Class': ['First Class', 'Second Class'],
    'Sex': 'Female'
};

d3.csv("data.csv", function(csv) {
    csv = csv.filter(function(row) {
        // run through all the filters, returning a boolean
        return ['Class','Age','Sex','Survived'].reduce(function(pass, column) {
            return pass && (
                // pass if no filter is set
                !filters[column] ||
                    // pass if the row's value is equal to the filter
                    // (i.e. the filter is set to a string)
                    row[column] === filters[column] ||
                    // pass if the row's value is in an array of filter values
                    filters[column].indexOf(row[column]) >= 0
                );
        }, true);
    })
    console.log(csv.length, csv);
});

(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 csv in memory somewhere and filter it on the fly, perhaps in an update() function triggered by user interactions.


Related Query

More Query from same tag