Created
May 13, 2018 07:35
-
-
Save thinkgarden/44d1ef85b2f43866839390f04e29385e to your computer and use it in GitHub Desktop.
Array to CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | |
// console.log(twoDiArray[i][j]) | |
// temp[i][j] = '\"' + `${dateFns.format(twoDiArray[i][j].timestamp,'HH:mm:ss')}` + '\"'; // Handle elements that contain comma | |
// } | |
// csvRows.push(temp[i].join(',')); | |
// } | |
for(var i = 0; i < twoDiArray.length; ++i) { | |
const times = twoDiArray[i].data.map(item => dateFns.format(item.timestamp,'HH:mm:ss')); | |
const values = twoDiArray[i].data.map(item => item.value); | |
csvRows.push(times.join(',')); | |
csvRows.push(values.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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment