To convert JavaScript array to CSV, we clal the map
and join
methods.
For instance, we write
const testArray = [
["name1", 2, 3],
["name2", 4, 5],
["name3", 6, 7],
["name4", 8, 9],
["name5", 10, 11],
];
const csv = testArray.map((row) => row.join(",")).join("\n");
to call testArray.map
with a callback that joins the array entries into a comma separated string with row.join(",")
.
And then we combine the row strings into a CSV string by calling join
with '\n'
.