How to convert array into comma separated string in javascript

JavascriptArrays

Javascript Problem Overview


I have an array

a.value = [a,b,c,d,e,f]

How can I convert to comma seperated string like

a.value = "a,b,c,d,e,f"

Thanks for all help.

Javascript Solutions


Solution 1 - Javascript

The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref

var array = ['a','b','c','d','e','f'];
document.write(array.toString()); // "a,b,c,d,e,f"

Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:

//will implicitly call array.toString()
str = ""+array;
str = `${array}`;

Array.prototype.join()

The join() method joins all elements of an array into a string.

Arguments:

It accepts a separator as argument, but the default is already a comma ,

str = arr.join([separator = ','])
Examples:
var array = ['A', 'B', 'C'];
var myVar1 = array.join();      // 'A,B,C'
var myVar2 = array.join(', ');  // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join('');    // 'ABC'
Note:

> If any element of the array is undefined or null , it is treated as an empty string.

Browser support:

It is available pretty much everywhere today, since IE 5.5 (1999~2000).

References

Solution 2 - Javascript

Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

Solution 3 - Javascript

You can simply use JavaScripts join() function for that. This would simply look like a.value.join(','). The output would be a string though.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavidView Question on Stackoverflow
Solution 1 - JavascriptVitim.usView Answer on Stackoverflow
Solution 2 - JavascriptGeeky GuyView Answer on Stackoverflow
Solution 3 - JavascriptAer0View Answer on Stackoverflow