Convert array to comma separated string using JavaScript
Question:
How to convert array to comma separated string using JavaScript? Answer:
const myArray = ['apple', 'orange', 'banana', 'ananas'];
const csv1 = String(myArray); // apple,orange,banana,ananas
const csv2 = myArray.toString(); // apple,orange,banana,ananas
const csv3 = myArray.join(); // apple,orange,banana,ananas
const csv4 = myArray.join('; '); // apple; orange; banana; ananas
Description:
The easiest way to create CSV text from a plain array is to use the toString
method or the String
constructor in JavaScript. The advantage of the String constructor is that you do not have to check if the variable is indeed an array.
If you want a little more freedom, you can use the join
method. The join()
method creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
The separator can be any character, and you can even use a multi-character string.
Reference:
Array join reference
Share "How to convert array to comma separated string using JavaScript?"
Related snippets:
- Check if an array contains a value
- Append an array to another in JavaScript
- Get the first element of an array in JavaScript
- Convert Map values to array in JavaScript
- Convert array to comma separated string using JavaScript
- Get the minimum value in an array using JavaScript
- Get the maximum value in an array using JavaScript
- Remove duplicates from array in JavaScript
- Split a string into words
- Use foreach in JavaScript
Tags:
convert, array, csv, comma separated string, join, javascript Technical term:
Convert array to comma separated string using JavaScript