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

363
Views
Download an array as a CSV, but the data inside the array has commas in it

I have an array of arrays, which looks something like this:

rows = [
        [Name, Description, Number ...],
        ["A thing", "Description, but it has commas in it", 6, ...],
        ...
       ]

I am trying to download this as a csv file. Here's the code I have so far:

// Make a csv from rows
let csv = rows.map(row => row.join(",")).join("\n");

document.getElementById("csv_download").setAttribute("download", "file_name.csv");

document.getElementById("csv_download").href = "data:text/csv;charset=utf-8," + encodeURIComponent(csv);

This works fine when there are no commas inside the array, but right now it sees the comma after "Description" and splits it there. I also can't split it by ", because some of the items are numbers.

How do I go about solving this?

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

0

How do I go about solving this?

It varies. CSV is not a fully standardized format. But it will involve escaping those commas in the data in some way.

The most common way is to surround the fields that have commas with double quotes. If the data also has double quotes in it, you "escape" them with another double quote.

Applying that to your code:

let csv = rows.map(
    row => row.map(
        col => typeof col !== "string" ? col : `"${col.replace(/"/g, '""')}"`
    ).join(",")
).join("\n");

const rows = [
    ["Name", "Description", "Number"],
    ["A thing", "Description, but it has \"commas\" in it", 6],
];
let csv = rows.map(
    row => row.map(
        col => typeof col !== "string" ? col : `"${col.replace(/"/g, '""')}"`
    ).join(",")
).join("\n");
console.log(csv);

But again, that's just one way to handle it.

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!