Home > Net >  How to turn an array to a CSV string based on commas?
How to turn an array to a CSV string based on commas?

Time:04-24

I have a function which returns a CSV string to be consumed by

anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvContent)}`

If I have an array like this:-

[
    [
        "Test,Me,Once,More",
        "Successful"
    ],
    [
        "Test1,Me1,Once1,More1",
        "Successful"
    ]
]

The construction of CSV string messes up when I have commas in my item. I cannot set a condition based on the number of commas because it's not fixed as a user requirement. I'm using the following function:-

function toCsv(arr) {
  return arr.reduce((csvString, row) => {
    csvString  = row.join(',');
    csvString  = '\r\n';
    return csvString;
  }, '');
}

This will return:-

Test,Me,Once,More,Successful
Test1,Me1,Once1,More1,Successful

Which when I download as CSV enter image description here

I wish to club Test, Me, Once, More as one item in CSV keeping the commas as it is like this: enter image description here

CodePudding user response:

RFC 4180 specifies that when you use the delimiter character in your fields (in your case it's the comma), you need to enclose the field in double quotation marks

In your case your text file output needs to look like this:

"Test,Me,Once,More",Successful
"Test1,Me1,Once1,More1",Successful

You can even enclose the Successful in double quotes.

You also need to use double quotes when having a line break in your cell but don't expect all CSV interpreters (e.g. Excel) to import line-break cells properly.

CodePudding user response:

As Dee J. Doena has stated, you should apply quotes "" to all string values. This snippet gives a simple short example of iterating an array of arrays and returning a CSV string;

let arr = [ [ "Test,Me,Once,More", "Successful", 123 ], [ "Test1,Me1,Once1,More1", "Successful", 234 ] ];

let csvConvert = () => {
    return arr.flatMap(t => t.map(o => typeof o  === "string" ? `"${o}"` : o).join(",")).join("\n")
}

let anchorEle = document.getElementById("csvLink")
anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvConvert())}`;
<a id="csvLink" href="#">Download CSV</a>

  • Related