Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Converts a 2D array into a CSV file
function arrayToCSV (twoDiArray) {
// Modified from:
// 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
var csvString = csvRows.join('\r\n');
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + csvString; = '_blank'; = 'myFile.csv';
// Optional: Remove <a> from <body> after done

This comment has been minimized.

Copy link

@ozmad 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
You can’t perform that action at this time.