Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to turn JavaScript array into comma-separated list?

Tags:

javascript

I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)

like image 760
Herb Caudill Avatar asked Oct 14 '08 15:10

Herb Caudill


People also ask

How do you add comma separated values in an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do I convert an array to a string without commas?

To convert an array to a string without commas, call the join() method on the array, passing it an empty string as a parameter - arr. join('') . The join method returns a string containing all array elements joined by the provided separator.

What does .join do in JavaScript?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How do you turn an array into a string?

To convert a JavaScript array into a string, you can use the built-in Array method called toString . Keep in mind that the toString method can't be used on an array of objects because it will return [object Object] instead of the actual values.


2 Answers

The Array.prototype.join() method:

var arr = ["Zero", "One", "Two"];    document.write(arr.join(", "));
like image 153
Wayne Avatar answered Oct 08 '22 09:10

Wayne


Actually, the toString() implementation does a join with commas by default:

var arr = [ 42, 55 ]; var str1 = arr.toString(); // Gives you "42,55" var str2 = String(arr); // Ditto 

I don't know if this is mandated by the JS spec but this is what most pretty much all browsers seem to be doing.

like image 23
Ates Goral Avatar answered Oct 08 '22 08:10

Ates Goral