Skip to content

Instantly share code, notes, and snippets.

@yangshun
Last active January 18, 2021 15:22
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save yangshun/01b81762e8d30f0d7f8f to your computer and use it in GitHub Desktop.
Save yangshun/01b81762e8d30f0d7f8f to your computer and use it in GitHub Desktop.
Converts a 2D array into a CSV file
function arrayToCSV (twoDiArray) {
// Modified from: http://stackoverflow.com/questions/17836273/
// export-javascript-data-to-csv-file-without-server-interaction
var csvRows = [];
for (var i = 0; i < twoDiArray.length; ++i) {
for (var j = 0; j < twoDiArray[i].length; ++j) {
twoDiArray[i][j] = '\"' + twoDiArray[i][j] + '\"'; // Handle elements that contain commas
}
csvRows.push(twoDiArray[i].join(','));
}
var csvString = csvRows.join('\r\n');
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + csvString;
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
// Optional: Remove <a> from <body> after done
}
@ozmad
Copy link

ozmad commented Apr 28, 2018

Note that in the inner loop, avoid modifying the original array. Use a temporary array or use map instead of for loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment