tao.hong tao.hong - 2 months ago 5
Javascript Question

Extra comma when concatenate JavaScript Arrays

I am trying to write a few

JavaScript
arrays into a CSV file. However, I need to add line break at certain locations. The following code works, but it accidently add
,
as the first element in Row 2 (or say it add
,
since Row 2). I am wondering what caused this? Thanks in advance!

current output



Chemical, CAS, MW
, water, 00566, 666


desire output



Chemical, CAS, MW
water, 00566, 666


code



var Chem1 = "water"
var CAS1 = "00566"
var MW1 = "666"

var csv_content = []
var csv_content_final = []
csv_content[0] = ["Chemical, CAS, MW"];
var chem_property = [Chem1, CAS1, MW1];
csv_content[1] = chem_property;
for (kkk = 0; kkk < ($(csv_content).size()); kkk++) {
csv_content_final[kkk] = csv_content[kkk] + '\n';
}

alert(csv_content_final)


JSFIDDLE

Pat Pat
Answer

The reason for the , is because by definition the CSV format is 'Comma Separated Values'

A new line is not considered a delimiter, only a comma.

EDIT:

If you REALLY want to not have a comma at the start, this will work: console.log(csv_content_final.join(''));

http://fiddle.jshell.net/L8zdqo4u/

But this is not CSV

enter image description here

Comments