Convert Array to CSV in JavaScript

- 1 minute read

The below toCSV function converts a given array to a CSV-compatible string:

const toCSV = (array, hasQuotes) => {
    return array.map((row) => row.map((cell) => !!hasQuotes ? `"${cell}"`: cell.toString()).join(`,`)).join(`\n`);
};

The toCSV function has two parameters. The first is the array to reformat, and the second is a boolean, which if true, will wrap each value in double quotation marks.

Here is some example usage:

const rowA = [
    `fruit`,
    `apple`
];

const rowB = [
    `color`,
    `red`
];

const array = [
    rowA,
    rowB
];

toCSV(array, false); // Returns `color,red\nfruit,apple`

toCSV(array, true); // Returns `"color","red"\n"fruit","apple"`

As demonstrated in the above example, it’s important to ensure that the array you provide is two-dimensional. In other words, the array you pass must be an array of arrays. Otherwise, an error will be thrown.

Link to this section Conclusion

And that is how I go about converting my JavaScript arrays to CSV. Thanks for reading!