Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #Array #HowTo

How to convert array to comma separated string in javascript

In this article, you are going to learn an efficient method to transform a JavaScript array into a comma-separated list.

Using the join() Method

The join() method in JavaScript allows you to convert an array into a string by specifying a delimiter, in this case, a comma.

<script>
 const myArray = ['apple', 'banana', 'cherry'];
 const commaSeparatedList = myArray.join(',');
 console.log(commaSeparatedList)
</script>

Explanation:

  1. We define an array called myArray.
  2. We use the join() method and pass a comma , as the delimiter to create a comma-separated list.

Using a for Loop

You can also achieve this by iterating through the array elements and manually building the comma-separated list.

<script>
 const myArray = ['apple', 'banana', 'cherry'];
 let commaSeparatedList = '';

 for (let i = 0; i < myArray.length; i++) {
  commaSeparatedList += myArray[i];
  if (i < myArray.length - 1) {
    commaSeparatedList += ',';
  }
 }
 console.log(commaSeparatedList)
</script>

Explanation:

  1. We define an empty string commaSeparatedList.
  2. We loop through the array elements and concatenate each element to the string.
  3. We add a comma , after each element except the last one to create the list.

In conclusion, you've learned two methods to turn a JavaScript array into a comma-separated list: using the join() method and a for loop.

save
listen
AI Answer
1 Answer
Write Your Answer
  1. Using the Array.prototype.join() method:
    <script>
    const arr = ["Zero", "One", "Two"];
    document.write(arr.join(", "));
    </script>
    Reply Delete
    Share
loading
back
View All