0

I'm currently trying to export a Javascript Array into a CSV file in order to load it into Excel.

The Array is like this :

var data = [
  [
    ['timestamp1', 'value1'], 
    ['timestamp2 ', 'value2']
  ],
  [
    ['timestamp1', 'value1'], 
    ['timestamp2 ', 'value2']
  ],
  [ 
    ['timestamp1', 'value1'], 
    ['timestamp2 ', 'value2']
  ]
];

And what I'd like as a result is something like this :

t1 v1   t1 v1   t1 v1
t2 v2   t2 v2   t2 v2

I've done some research and tried an example :

var csvContent = '';
var dataString;
data. (function (infoArray) {
  dataString = infoArray.join(';');
  csvContent += dataString + "\n";
});

But it doesn't seem to work with this kind of multiple-dimensional array.

Does anyone have a clue of a working solution ?

Thanks a lot in advance.

SaschaM78
  • 4,104
  • 3
  • 31
  • 38
JourdanM
  • 57
  • 4
  • 1
    Possible duplicate of [How to export JavaScript array info to csv (on client side)?](https://stackoverflow.com/questions/14964035/how-to-export-javascript-array-info-to-csv-on-client-side) – VLAZ May 17 '19 at 11:45
  • 1
    csv is `comma separated file` but your output and logic both do not seem to use `,`. – AZ_ May 17 '19 at 11:46

1 Answers1

0

That's doable of course. What makes it a little more difficult in your case is that it's a three-dimensional array. Well basically you just need two for-loops and compose a string out of the elements.

var data = [
  [
    ['timestamp1', 'value1'],
    ['timestamp2', 'value2']
  ],
  [
    ['timestamp1', 'value1'],
    ['timestamp2', 'value2']
  ],
  [
    ['timestamp1', 'value1'],
    ['timestamp2', 'value2']
  ]
];
var csvContent = "";
for (var a = 0; a < data[0].length; a++) {
  if (a != 0) {
    csvContent += "\n";
  }
  for (var b = 0; b < data.length; b++) {
    csvContent += data[b][a][0] + "," + data[b][a][1] + ",";
  }
}
console.log(csvContent);
obscure
  • 8,071
  • 2
  • 9
  • 30