A CSV is a comma-separated values file, which provides data to be saved in a tabular format. In addition, the CSV files are plain-text files, making them easier for the website developer to create. Let’s see how to create csv values from an array.
The array.toString() method does not take any parameters.
The array.toString() method returns a String, representing the array’s values, separated by a comma.
Let’s declare an array and convert it into the csv using an array.toString() method.
let moneyheist = ["Tokyo", "Nairobi", "Berlin", "Oslo", "Moscow"] let moneyheist_csv = moneyheist.toString() console.log(moneyheist_csv)
The toString() method converts an array into a csv string and returns that output. The output string is filled with array values separated by commas.
Using join() method
The join() function joins the items of an array into a string and returns the string.
The separator is an optional parameter. If omitted, the elements are separated with a comma.
It returns a string representing the array values, separated by the specified separator.
let moneyheist = ["Tokyo", "Nairobi", "Berlin", "Oslo", "Moscow"] let moneyheist_csv = moneyheist.join() console.log(moneyheist_csv)
You can see from the output that, by default, the array.join() method returns a string separated by a comma, but you can pass whatever separator you want, and it will return the string separated by the provided value.