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:
- We define an array called myArray.
- 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:
- We define an empty string commaSeparatedList.
- We loop through the array elements and concatenate each element to the string.
- 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
How to convert array to comma separated string in javascript
1
In this article, you are going to learn an efficient method to transform a JavaScript arr…
asked
Apu
1 answers
2915
In this article, you are going to learn an efficient method to transform a JavaScript arr…
Answer Link
answered
Apu
<script>
const arr = ["Zero", "One", "Two"];
document.write(arr.join(", "));
</script>