Export a JavaScript array as a CSV file on the client-side

OpenJavaScript 0
Reading Time: 2 minutes 🕑

Last updated: July 24, 2022.

There is no dedicated native solution for converting a JavaScript array to CSV format.

But using the join() method, you can convert a JavaScript array to CSV format.

Table of contents

Convert an array to CSV format

First, make sure your data is formatted to contain as many nested arrays as rows. The row data should be defined in each nested array.

const data = [
    ["John", "Liverpool", "Guitar"],
    ["Ringo", "Liverpool", "Percussion"],
    ["Paul", "Liverpool", "Bass"],
    ["George", "Liverpool", "Guitar"],
];

The first step is to iterate through each item in data (a nested array), applying join(",") each time.

This merges all items in each nested array into a string, with each item separated by a comma.

let rowsAsString = data.map(row => {
    return row.join(",");
})

console.log(rowsAsString);
// [
//   "John,Liverpool,Guitar",
//   "Ringo,Liverpool,Percussion",
//   "Paul,Liverpool,Bass",
//   "George,Liverpool,Guitar"
// ]

The result is an array with four items.

Use join("\n") to merge these items into a single string, with each item separated by a line break:

let csvFormat = rowsAsString.join("\n");

console.log(csvFormat);
// John,Liverpool,Guitar
// Ringo,Liverpool,Percussion
// Paul,Liverpool,Bass
// George,Liverpool,Guitar

As a reusable utility function

To make the process of converting an array to CSV format repeatable, you can create a utility function.

In the function below, the first parameter is the array to be converted, and the second is the separator. Unless otherwise specified, comma-separation is used:

const data = [
    ["John", "Liverpool", "Guitar"],
    ["Ringo", "Liverpool", "Percussion"],
    ["Paul", "Liverpool", "Bass"],
    ["George", "Liverpool", "Guitar"],
];

function toCSV(inputArray, separator = ",") {

    let rowsAsString = inputArray.map(row => {
    return row.join(separator);
    })

    return csvFormat = rowsAsString.join("\n");

}


toCSV(data);
// John,Liverpool,Guitar
// Ringo,Liverpool,Percussion
// Paul,Liverpool,Bass
// George,Liverpool,Guitar

toCSV(data, "|");
// John|Liverpool|Guitar
// Ringo|Liverpool|Percussion
// Paul|Liverpool|Bass
// George|Liverpool|Guitar

Exporting CSV as a download

To make the result available as a download, first create a new link element (<a>).

Usually, this would be used to link to another page. But here, the link will be the CSV-formatted string.

To do so, set the href attribute on the link element. The first part should be 'data:text/csv;charset=utf-8,'. This is so when the link is clicked, the user's browser recognizes that this is not a URL, but text data in CSV format.

The second part should be the CSV-formatted string.

Finally, if you want to name the file, you can set the download attribute on the link element to the desired name.

/* Create new link element */
const downloadLink = document.createElement('a');
downloadLink.textContent = "Download CSV file!";

/* Set attributes */
// 'href' attribute specifies that it is text data in CSV format:
downloadLink.setAttribute('href', 'data:text/csv;charset=utf-8,' + csvFormat);
// 'download' attribute sets a file name:
downloadLink.setAttribute('download', 'test-csv.csv');

// Append the result to DOM
document.body.append(downloadLink);

Now, when a user clicks on the link element in the DOM, the data will be opened as a file with the given name in the user's default program for opening CSV files.