You are currently viewing How to Convert Array to String with Comma in JavaScript

How to Convert Array to String with Comma in JavaScript

Three Methods to Convert an Array to String With Comma

In this article, we will see how to convert an array to a string with a comma in javascript. I have 3 different solutions for this problem.

Using join: Method 1

let subjects=["Maths", "Physics", "chemistry","Hindi","Biology","English"];

var sub=subjects.join(", ");
document.write(sub);

//Output:
//Maths, Physics, chemistry, Hindi, Biology, English
  1. In the above code, we have an array of “subjects” with 6 values.
  2. To convert an array to a string with a comma in javascript, we use the “join” method to bring the array to the variable “sub”.
  3. A comma must be placed after using the join method to separate each string.
  4. And print the sub using document.write method. Since all the values ​​in the array are converted to the string “sub”, the values in the array(subjects) are displayed as output.

For loop: Method 2

let subjects=["Maths", "Physics", "chemistry","Hindi","Biology","English"];

var sub="";
for(var i=0; i<subjects.length; i++){
var subName=subjects[i] + ', ';
sub+=subName; // sub = sub + subName
}
document.write(sub);

//Output:
//Maths, Physics, chemistry, Hindi, Biology, English

Steps:

  1. In the above code, we have an array “subjects”. First, we initialize the Empty value to the string “sub”.
  2. Then create for loop with condition 0 to array length. Inside the loop, we have created another string called “subName”.
  3. Add array(subjects) with index value in “var”. Then all the values ​​in the variable “subName” are transferred to the variable “sub” using the concatenation operator.
  4. Finally, printing the variable “sub” outside the loop.

Function: Method 3

let subjects=["Maths", "Physics", "chemistry","Hindi","Biology","English"];

var sub="";
subjects.forEach(function(item, index){
var seperator=(subjects.length-1==index)?"" : ", " ;
var subName=item+seperator;
sub+=subName;
})
document.write(sub)

//Output:
//Maths, Physics, chemistry, Hindi, Biology, English
  1. Steps:

 

  1. In the above code, we have an array of subjects.
  2. First, we initialize the Empty value to the string “sub”.
  3. Then create a function using “forEach” method for an array(subjects) with passing the “item and index” parameter.
  4. Inside the function, we have created two other stings to store the array value one by one into string “Sub”.
  5. And print the String “sub” outside the function.

Leave a Reply