Created
April 18, 2023 11:21
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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