I\'ve followed this post How to export JavaScript array info to csv (on client side)? to get a nested js array written as a csv file.
The array looks like:
ES6:
let csv = test_array.map(row=>row.join(',')).join('\n')
//test_array being your 2D array
The selected answer is probably correct but it seems needlessly unclear.
I found Shomz's Fiddle to be very helpful, but again, needlessly unclear. (Edit: I now see that that Fiddle is based on the OP's Fiddle.)
Here's my version (which I've created a Fiddle for) which I think is more clear:
function downloadableCSV(rows) {
var content = "data:text/csv;charset=utf-8,";
rows.forEach(function(row, index) {
content += row.join(",") + "\n";
});
return encodeURI(content);
}
var rows = [
["name1", 2, 3],
["name2", 4, 5],
["name3", 6, 7],
["name4", 8, 9],
["name5", 10, 11]
];
$("#download").click(function() {
window.open(downloadableCSV(rows));
});
General form is:
var ids = []; <= this is your array/collection
var csv = ids.join(",");
For your case you will have to adapt a little bit
for a simple csv one map() and a join() are enough:
var csv = test_array.map(function(d){
return d.join();
}).join('\n');
/* Results in
name1,2,3
name2,4,5
name3,6,7
name4,8,9
name5,10,11
This method also allows you to specify column separator other than a comma in the inner join
. for example a tab: d.join('\t')
On the other hand if you want to do it properly and enclose strings in quotes ""
, then you can use some JSON magic:
var csv = test_array.map(function(d){
return JSON.stringify(d);
})
.join('\n')
.replace(/(^\[)|(\]$)/mg, ''); // remove opening [ and closing ] brackets from each line
/* would produce
"name1",2,3
"name2",4,5
"name3",6,7
"name4",8,9
"name5",10,11
if you have array of objects like :
var data = [
{"title": "Book title 1", "author": "Name1 Surname1"},
{"title": "Book title 2", "author": "Name2 Surname2"},
{"title": "Book title 3", "author": "Name3 Surname3"},
{"title": "Book title 4", "author": "Name4 Surname4"}
];
// use
var csv = data.map(function(d){
return JSON.stringify(Object.values(d));
})
.join('\n')
.replace(/(^\[)|(\]$)/mg, '');
The following code were written in ES6 and it will work in most of the browsers without an issue.
var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];
// Construct the comma seperated string
// If a column values contains a comma then surround the column value by double quotes
const csv = test_array.map(row => row.map(item => (typeof item === 'string' && item.indexOf(',') >= 0) ? `"${item}"`: String(item)).join(',')).join('\n');
// Format the CSV string
const data = encodeURI('data:text/csv;charset=utf-8,' + csv);
// Create a virtual Anchor tag
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', 'export.csv');
// Append the Anchor tag in the actual web page or application
document.body.appendChild(link);
// Trigger the click event of the Anchor link
link.click();
// Remove the Anchor link form the web page or application
document.body.removeChild(link);
const escapeString = item => (typeof item === 'string') ? `"${item}"` : String(item)
const arrayToCsv = (arr, seperator = ';') => arr.map(escapeString).join(seperator)
const rowKeysToCsv = (row, seperator = ';') => arrayToCsv(Object.keys(row))
const rowToCsv = (row, seperator = ';') => arrayToCsv(Object.values(row))
const rowsToCsv = (arr, seperator = ';') => arr.map(row => rowToCsv(row, seperator)).join('\n')
const collectionToCsvWithHeading = (arr, seperator = ';') => `${rowKeysToCsv(arr[0], seperator)}\n${rowsToCsv(arr, seperator)}`
// Usage:
collectionToCsvWithHeading([
{ title: 't', number: 2 },
{ title: 't', number: 1 }
])
// Outputs:
"title";"number"
"t";2
"t";1