Table of Contents
In the previous article, we have seen how to convert an array to an object in JavaScript. In this article, we will see different methods of converting arrays into a string. We will explore approaches using a comma and without using a comma.
Using toString function
The first choice to convert an array into a comma-separated string is toString function offered by arrays.
1const array1 = ["Apple", "Banana", "Grapes", "Orange"]2console.log(array1.toString()) // 👉️ Apple,Banana,Grapes,Orange
The major drawback of using toString
function is that you cannot specify the separator you want.
It is always a comma and you cannot even add a space after the comma.
Using join function
When you need to specify a separator, you can use join function.
1const array1 = ["Apple", "Banana", "Grapes", "Orange"]2console.log(array1.join()) // 👉️ Apple,Banana,Grapes,Orange
As you can see above, if you do not specify the separator it works the same as toString
function.
You can specify space as a separator as shown below:
1const array1 = ["Apple", "Banana", "Grapes", "Orange"]23console.log(array1.join(" ")) // 👉️ Apple Banana Grapes Orange
You can specify other separators you like as well (say, pipe symbol):
1const array1 = ["Apple", "Banana", "Grapes", "Orange"]23console.log(array1.join("|")) // 👉️ Apple|Banana|Grapes|Orange
By appending/prepending an empty string
If you like some hacky way to achieve it, you can do so by appending/prepending an empty string as shown below:
1const array1 = ["Apple", "Banana", "Grapes", "Orange"]23console.log(array1 + "") // 👉️ Apple,Banana,Grapes,Orange45console.log("".concat(array1)) // 👉️ Apple,Banana,Grapes,Orange
In most cases, join
function should solve your problem. If you know any other methods, comment below.
Do follow me on twitter where I post developer insights more often!
Leave a Comment