Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array to CSV

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:

var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];

The code given in the link works nicely except that after the third line of the csv file all the rest of the values are on the same line e.g.

name1,2,3
name2,4,5
name3,6,7
name4,8,9name5,10,11 etc etc

Can anyone shed any light on why this is? Same using Chrome or FF.

Thanks

EDIT

jsfiddle http://jsfiddle.net/iaingallagher/dJKz6/

Iain

like image 696
duff Avatar asked Oct 06 '22 14:10

duff


1 Answers

The cited answer was wrong. You had to change

csvContent += index < infoArray.length ? dataString+ "\n" : dataString;

to

csvContent += dataString + "\n";

As to why the cited answer was wrong (funny it has been accepted!): index, the second parameter of the forEach callback function, is the index in the looped-upon array, and it makes no sense to compare this to the size of infoArray, which is an item of said array (which happens to be an array too).

EDIT

Six years have passed now since I wrote this answer. Many things have changed, including browsers. The following was part of the answer:

START of aged part

BTW, the cited code is suboptimal. You should avoid to repeatedly append to a string. You should append to an array instead, and do an array.join("\n") at the end. Like this:

var lineArray = [];
data.forEach(function (infoArray, index) {
    var line = infoArray.join(",");
    lineArray.push(index == 0 ? "data:text/csv;charset=utf-8," + line : line);
});
var csvContent = lineArray.join("\n");

END of aged part

(Keep in mind that the CSV case is a bit different from generic string concatenation, since for every string you also have to add the separator.)

Anyway, the above seems not to be true anymore, at least not for Chrome and Firefox (it seems to still be true for Safari, though).

To put an end to uncertainty, I wrote a jsPerf test that tests whether, in order to concatenate strings in a comma-separated way, it's faster to push them onto an array and join the array, or to concatenate them first with the comma, and then directly with the result string using the += operator.

Please follow the link and run the test, so that we have enough data to be able to talk about facts instead of opinions.

like image 123
Walter Tross Avatar answered Oct 12 '22 12:10

Walter Tross