1

I have the following map and filter functions in order to get my csv file data with their column names as keys.

d3.csv("Sales Export Friendly 3-19-17.csv", function(data) {
    sales = data
        .map(sale => [
        sale["Unit Booked"],
        new Date(sale["Booking Date"]).getMonth() + 1,
        new Date(sale["Checkin"]).getMonth() + 1,
        (new Date(sale["Checkout"]).valueOf() - new Date(sale["Checkin"]).valueOf())/(24*60*60*1000),
        +sale["Total Stay"],
        (+sale["Total Stay"]) / ((new Date(sale["Checkout"]).valueOf() - new Date(sale["Checkin"]).valueOf())/(24*60*60*1000)),
        ])
        .filter(([unit, date, checkin, LOS, total, avgNight]) => !isNaN(total));

This works for most purposes but I haven't figured out how to retain the column names to reference them as axes in a d3 multidimensional type of viz (parallel coordinates). I think it may have to do with the use of map and filter?

Frederic Bastiat
  • 695
  • 4
  • 12
  • 31

1 Answers1

1

When you load a CSV file, d3.csv creates a handy array property called columns.

According to the API:

The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).

Thus, since your callback parameter is named data, you can get the columns' names simply using:

data.columns

Or assigning it to a variable:

var myColumns = data.columns

Here is a demo with a real CSV file from this Bostock's bl.ocks:

d3.csv("https://gist.githubusercontent.com/mbostock/3887051/raw/805adad40306cedf1a513c252ddd95e7c981885a/data.csv", function(data){
  console.log(data.columns);
});
<script src="https://d3js.org/d3.v4.min.js"></script>

PS: this answer refers to D3 v4, which should be the default version for answers, unless stated otherwise in the question.

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • Thank you, this helped move me along. I do need some help parsing the date columns now if you can help there: http://stackoverflow.com/questions/42990052/parsing-dates-using-time-in-d3 – Frederic Bastiat Mar 24 '17 at 05:20