Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.)

share|improve this question

3 Answers

up vote 120 down vote accepted

The join function:

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

document.write(arr.join(","));
share|improve this answer
13  
Noooooooooo! Tempted to downvote. What if the strings contain commas?! They need to be quoted. – Mark Dec 2 '11 at 16:19
2  
@davewilliams459: But you're not the OP? Op said "a one-dimensional array of strings". Strings. Not IDs. That implies they could be anything. Which means they may contain other commas. – Mark Feb 8 '12 at 16:26
3  
@Mark: The answer is correct for the question as asked. Any other requirements are left to the individual to work out for themselves. OP asked for a comma-separated list, not a quoted CSV-type format. – Wayne Feb 10 '12 at 22:37
4  
@Wayne: I still think a warning is in order :) People don't always think these things through, and then they shoot themselves in the foot later. – Mark Feb 10 '12 at 22:54
1  
@Mark - your comment is perfectly valid (as others have indicated with an upvote) but more helpful might have been to actually provide the alternative answer with example code? – Chris Jul 8 '12 at 10:06
show 2 more comments

Or (more efficiently):

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

document.write(arr); // same as document.write(arr.toString()) in this context

The toString method of an array when called returns exactly what you need - comma-separated list.

share|improve this answer
In most cases, toString is actually slower than array join. Lookie here: jsperf.com/tostring-join – Sameer Alibhai Jul 9 at 19:10

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.

share|improve this answer
1  
array join is faster jsperf.com/tostring-join – Sameer Alibhai Jul 9 at 19:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.