Here we have a couple of inquiries:
- How can we transform an array into a csv string?
- How do we store that string in a file?
Most solutions provided for the first question (except Milimetric's) appear to be overly complex. Milimetric's answer, on the other hand, lacks coverage of alternative requirements such as wrapping strings with quotes or handling arrays of objects.
Below are my approaches to this problem:
For a straightforward csv conversion, using map() and join() is sufficient:
var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];
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 a different column separator within the join function, like a tab: d.join('\t')
Alternatively, for a more thorough approach involving enclosing strings in quotes "", JSON magic comes in handy:
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 dealing with an 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"}
];
// utilize
var csv = data.map(function(d){
return JSON.stringify(Object.values(d));
})
.join('\n')
.replace(/(^\[)|(\]$)/mg, '');