Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
How to turn an array to a CSV string based on commas?

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!