0

I need to populate a 2d array, e.g.,

var dataset = [[1,3,3,5,6,7],[3,5,8,3,2,6],[9,0,6,3,6,3],[3,4,4,5,6,8],[3,4,5,2,1,8]];

Where the information comes from external sources, while I have the control in the format to store them (csv,json etc., to be read by functions like d3.csv, d3.json etc.).

What are the simplest ways to store 2d array in external files, and to read in to populate the variable like dataset when doing d3 processing?

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
william007
  • 17,375
  • 25
  • 118
  • 194

2 Answers2

3

You can do it using a CSV file, a TSV file, a XML file, a text file... However, I believe that the simplest way to store your array of arrays is just saving it (the way it is right now, no change, but without the semicolon of course) in a JSON file.

Therefore, if you ask what is the simplest way (and, if by simplest, you mean the way which requires less code to get the final result), JSON is by far the best choice.

Here is a plunker illustrating this (I can't use stack snippets to load JSON files), have a look at the console: https://plnkr.co/edit/2ksVXhnP8EFFHo8P1vrt?p=preview

The code is simply:

d3.json("data.json", function(data){
    console.log(data)
})

And the data.json file is just:

[
    [1, 3, 3, 5, 6, 7],
    [3, 5, 8, 3, 2, 6],
    [9, 0, 6, 3, 6, 3],
    [3, 4, 4, 5, 6, 8],
    [3, 4, 5, 2, 1, 8]
]
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
2

I guess it really depends on what "best way" means. D3 offers a variety of ways to load in data: csv, tsv, json. Since many APIs return JSON data these days, I like to stick to that format if I can. Should you choose to go that way, you can use the following D3 function:

d3.json("path/to/file.json", function(dataset) {
  // Data is now in dataset 
  console.log(dataset);
});

But of course you can do the exact same thing with csv or tsv.

Nick
  • 16,066
  • 3
  • 16
  • 32
  • Note that you might need to do [this](https://stackoverflow.com/questions/4819060/allow-google-chrome-to-use-xmlhttprequest-to-load-a-url-from-a-local-file) if you're developing in Chrome, or else you'll get an error preventing file access by files. – M. Davis Oct 08 '17 at 19:49
  • 1
    Or just set up a simple server like [http-server](https://www.npmjs.com/package/http-server) – Nick Oct 08 '17 at 19:51