How can I convert an array to a comma-separated string in JavaScript?
Davide S
davide s profile pic

To convert an array to a comma-separated string in JavaScript, you can use thejoin() method. Thejoin() method concatenates the elements of an array into a string, using a specified separator between each element. Here's how you can do it:

1
2
3
4
5
6
7

const array = ['apple', 'banana', 'orange'];

const commaSeparatedString = array.join(',');

console.log(commaSeparatedString);
// Output: "apple,banana,orange"

In the example above, thejoin() method is called on thearray and the separator',' is passed as an argument. The method concatenates the elements of the array with the specified separator in between, resulting in the comma-separated string. If you want to customize the separator or include additional characters, simply change the argument passed to thejoin() method. For example, if you want a comma followed by a space as the separator, you can modify the code like this:

1
2
3
4
5
6
7
8
9

const array = ['apple', 'banana', 'orange'];

const customSeparator = ', ';

const commaSeparatedString = array.join(customSeparator);

console.log(commaSeparatedString);
// Output: "apple, banana, orange"

By providing a custom separator, you can format the resulting string as per your requirements. Thejoin() method is a convenient way to convert an array to a comma-separated string in JavaScript.