Francis Bartkowiak
Francis Bartkowiak

Reputation: 1462

Read Array of Arrays Like CSV

If I have a CSV file that looks like this:

Year,Value1,Value2,Value3
2000,500,20,30
2001,40,30,20
2002,90,12,80
2003,70,55,22
...

I can read this in with D3 JS using the d3.csv("./file.csv").then(function (data)) method and I'll get data that looks like this:

[
    { Value1: "500", Value2: "20", Value3: "30", Year: "2000"},
    { Value1: "40", Value2: "30", Value3: "20", Year: "2001"},
    { Value1: "90", Value2: "12", Value3: "80", Year: "2002"},
    { Value1: "70", Value2: "55", Value3: "22", Year: "2003"}
]

This is great. It formats the data perfectly for what I need. Unfortunately for me, the incoming data I'll be working with is actually an array of arrays that will look like this:

[
    ["Year","Value1","Value2","Value3"],
    [2000,500,20,30],
    [2001,40,30,20],
    [2002,90,12,80],
    [2003,70,55,22]
]

Is there a built in method in D3 that will do to this array of arrays what the d3.csv() method does to CSV? As in, is there a method that will take in the array of arrays and turn it into an array of objects where each column header is associated with it's value in the given row?

So far the best solution I've come up with is to just turn the array of arrays into CSV and then parse it with D3 like this (I'm putting double quotes around each value in case of commas in values):

let csv = "";
for (const array of arrays) {
    csv += '"' + array.join('","') + '"\r\n';
}
const data = d3.csvParse(csv);

This just feels a bit clunky to me, so I'm wondering if there's a quicker way to do this.

Upvotes: 0

Views: 218

Answers (1)

slider
slider

Reputation: 12990

You can do this with pure JS, mapping each row to an object that you can build with reduce.

var data = [
  ["Year", "Value1", "Value2", "Value3"],
  [2000, 500, 20, 30],
  [2001, 40, 30, 20],
  [2002, 90, 12, 80],
  [2003, 70, 55, 22]
];

var result = data.slice(1)
  .map(row => row.reduce((acc, curr, i) => {
    acc[data[0][i]] = curr;
    return acc;
  }, {}));

console.log(result);

Upvotes: 2

Related Questions