Array to CSV

OSCC · JavaScript, Array, String · Nov 3, 2020

Converts a 2D array to a comma-separated values (CSV) string.

  • Use and Array.prototype.join() to combine individual 1D arrays (rows) into strings, using the provided delimiter.
  • Use Array.prototype.join() to combine all rows into a CSV string, separating each row with a newline (\n).
  • Omit the second argument, delimiter, to use a default delimiter of ,.
const arrayToCSV = (arr, delimiter = ',') =>
    .map(v => => (isNaN(x) ? `"${x.replace(/"/g, '""')}"` : x)).join(delimiter)
arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
arrayToCSV([['a', '"b" great'], ['c', 3.1415]]);
// '"a","""b"" great"\n"c",3.1415'

Recommended snippets

  • JSON to CSV

    JavaScript, Array

    Converts an array of objects to a comma-separated values (CSV) string that contains only the columns specified.

  • CSV to array

    JavaScript, String

    Converts a comma-separated values (CSV) string to a 2D array.

  • Array to flags object

    JavaScript, Array

    Converts an array of strings into an object mapping to true.