Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Created April 18, 2023 11:21
Show Gist options
  • Save isurfer21/966c8824bb287b036027c7479390d923 to your computer and use it in GitHub Desktop.
Save isurfer21/966c8824bb287b036027c7479390d923 to your computer and use it in GitHub Desktop.
This function takes an array of arrays as input and returns a CSV string. The first element of the input array is assumed to be the header row.
function convertArrayToCSV(arr) {
const arrayCopy = [...arr];
const header = arrayCopy.shift();
const csv = [
header.join(','),
...arrayCopy.map((row) => row.join(',')),
].join('\n');
return csv;
}
const data = [
['Name', 'Age', 'City'],
['John', '25', 'New York'],
['Jane', '30', 'Los Angeles'],
['Bob', '40', 'San Francisco'],
];
const csv = convertArrayToCSV(data);
console.log(csv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment