Here are the ways to convert an array to csv in JavaScript:
- Using Array.toString()
- Using Array.join()
- Using Array.split()
Method 1: Using the Array.toString() method
JavaScript Array toString() method returns a string representing the specified array and its elements. For a simple array, it will return comma-separated values.
const arr = [1, 2, 3, 4, 5];
const csv = arr.toString();
console.log(csv);
Output
1,2,3,4,5
Method 2: Using the Array.join() method
Use the combination of the Array.prototype.map() and Array.prototype.join() methods with a comma separator and new line character to convert to a string.
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
Method 3: Using the Array.split() method
This is incorrect in the context of converting an array to CSV. The split() method is used to split a string into an array of substrings based on a specified delimiter. It’s the opposite of what you’re trying to achieve.
To convert a 2D array (like a table) to CSV in JavaScript, it’s a bit more involved.
function arrayToCSV(data) {
return data.map(row => row.join(",")).join("\n");
}
const table = [
["Name", "Age", "City"],
["John", 25, "New York"],
["Jane", 30, "Los Angeles"]
];
console.log(arrayToCSV(table));
Output
That’s it!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.