How to Convert an Array to CSV in JavaScript

To convert an array to CSV (Comma-Separated Values) in JavaScript, you can use the combination of the “Array.prototype.map()” and “Array.prototype.join()” methods with a comma separator and new line character.

Example

const mainArray = [
  ['name', 'age', 'city'],
  ['Niva', 30, 'New York'],
  ['Khushi', 25, 'San Francisco'],
  ['Anjni', 19, 'Los Angeles']
];

const mainCSV = mainArray.map(row => row.join(',')).join('\n');

console.log(mainCSV);

Output

name,age,city
Niva,30,New York
Khushi,25,San Francisco
Anjni,19,Los Angeles

In this code, a mainArray is created with nested arrays, where the first nested array contains the column headers, and the subsequent nested arrays have the data rows.

The Array.prototype.map() method is called on mainArray to map each nested array to a string with comma-separated values using the Array.prototype.join() method with a comma separator.

The Array.prototype.join() method is then called on the resulting array of strings to join them into a single string with new line characters as the separator. Finally, the CSV string is logged to the console.

Leave a Comment