542

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

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
Herb Caudill
  • 50,043
  • 39
  • 124
  • 173
  • 4
    **toString()**: If you are looking for the simplest way it's better to use **toString()** like this: `var arr = ["Zero", "One", "Two"]; console.log(arr.toString());` which returns `Zero,One,Two` [Read more](https://www.w3schools.com/js/js_array_methods.asp) – Muhammad Musavi May 30 '18 at 06:34

22 Answers22

976

The Array.prototype.join() method:

var arr = ["Zero", "One", "Two"];

document.write(arr.join(", "));
Steel Brain
  • 4,321
  • 28
  • 38
Wayne
  • 38,646
  • 4
  • 37
  • 49
  • 2
    @Mark: true enough but I need to concatenate list of IDs, no chance of commas or other special chars – davewilliams459 Feb 08 '12 at 15:37
  • 11
    @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. – mpen Feb 08 '12 at 16:26
  • 23
    @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
  • 12
    @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. – mpen Feb 10 '12 at 22:54
  • 14
    @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 08 '12 at 10:06
  • @Chris: I don't think I'm obligated to provide an alternative just to point out the flaws in another solution. Nevertheless, [I have](http://stackoverflow.com/a/22313674/65387). – mpen Mar 10 '14 at 23:45
  • @Mark, you could always just delimit the strings with something that would probably never appear in their data, such as ";;;". – devinbost Sep 24 '14 at 19:35
  • @bostIT As long as you're *certain* it will never appear, yes, that's an easy solution. I just think it should at least be mentioned in the answer is all. – mpen Sep 24 '14 at 20:35
117

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.

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
38

Simple Array

let simpleArray = [1,2,3,4]
let commaSeperated = simpleArray.join(",");
console.log(commaSeperated);

Array of Objects with a particular attributes as comma separated.

let arrayOfObjects = [
{
id : 1,
name : "Name 1",
address : "Address 1"
},
{
id : 2,
name : "Name 2",
address : "Address 2"
},
{
id : 3,
name : "Name 3",
address : "Address 3"
}]
let names = arrayOfObjects.map(x => x.name).join(", ");
console.log(names);

Result

Name 1, Name 2, Name 3
jfk
  • 4,335
  • 34
  • 27
30

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.

Sergey Ilinsky
  • 31,255
  • 9
  • 54
  • 56
22

If you need to use " and " instead of ", " between the last two items you can do this:

function arrayToList(array){
  return array
    .join(", ")
    .replace(/, ((?:.(?!, ))+)$/, ' and $1');
}
Andrew Downes
  • 547
  • 7
  • 13
14

Here's an implementation that converts a two-dimensional array or an array of columns into a properly escaped CSV string. The functions do not check for valid string/number input or column counts (ensure your array is valid to begin with). The cells can contain commas and quotes!

Here's a script for decoding CSV strings.

Here's my script for encoding CSV strings:

// Example
var csv = new csvWriter();
csv.del = '\t';
csv.enc = "'";

var nullVar;
var testStr = "The comma (,) pipe (|) single quote (') double quote (\") and tab (\t) are commonly used to tabulate data in plain-text formats.";
var testArr = [
    false,
    0,
    nullVar,
    // undefinedVar,
    '',
    {key:'value'},
];

console.log(csv.escapeCol(testStr));
console.log(csv.arrayToRow(testArr));
console.log(csv.arrayToCSV([testArr, testArr, testArr]));

/**
 * Class for creating csv strings
 * Handles multiple data types
 * Objects are cast to Strings
 **/

function csvWriter(del, enc) {
    this.del = del || ','; // CSV Delimiter
    this.enc = enc || '"'; // CSV Enclosure

    // Convert Object to CSV column
    this.escapeCol = function (col) {
        if(isNaN(col)) {
            // is not boolean or numeric
            if (!col) {
                // is null or undefined
                col = '';
            } else {
                // is string or object
                col = String(col);
                if (col.length > 0) {
                    // use regex to test for del, enc, \r or \n
                    // if(new RegExp( '[' + this.del + this.enc + '\r\n]' ).test(col)) {

                    // escape inline enclosure
                    col = col.split( this.enc ).join( this.enc + this.enc );

                    // wrap with enclosure
                    col = this.enc + col + this.enc;
                }
            }
        }
        return col;
    };

    // Convert an Array of columns into an escaped CSV row
    this.arrayToRow = function (arr) {
        var arr2 = arr.slice(0);

        var i, ii = arr2.length;
        for(i = 0; i < ii; i++) {
            arr2[i] = this.escapeCol(arr2[i]);
        }
        return arr2.join(this.del);
    };

    // Convert a two-dimensional Array into an escaped multi-row CSV 
    this.arrayToCSV = function (arr) {
        var arr2 = arr.slice(0);

        var i, ii = arr2.length;
        for(i = 0; i < ii; i++) {
            arr2[i] = this.arrayToRow(arr2[i]);
        }
        return arr2.join("\r\n");
    };
}
skibulk
  • 3,088
  • 1
  • 34
  • 42
11

I think this should do it:

var arr = ['contains,comma', 3.14, 'contains"quote', "more'quotes"]
var item, i;
var line = [];

for (i = 0; i < arr.length; ++i) {
    item = arr[i];
    if (item.indexOf && (item.indexOf(',') !== -1 || item.indexOf('"') !== -1)) {
        item = '"' + item.replace(/"/g, '""') + '"';
    }
    line.push(item);
}

document.getElementById('out').innerHTML = line.join(',');

fiddle

Basically all it does is check if the string contains a comma or quote. If it does, then it doubles all the quotes, and puts quotes on the ends. Then it joins each of the parts with a comma.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 2
    Noooooooooo! Tempted to downvote. What if the quotes should be escaped with backslashes?! They need to be variable. ;) – Joshua Burns Apr 23 '14 at 22:36
  • 1
    @JoshuaBurns [wikipedia](https://en.wikipedia.org/wiki/Comma-separated_values#Toward_standardization) says double quotes should be escaped with another quote, but there is no formal standard. If your CSV reader requires something different, feel free to modify and/or downvote ;) – mpen Apr 24 '14 at 00:17
  • 5
    Actually there is an RFC, http://tools.ietf.org/rfc/rfc4180.txt, and that is correct double quotes should be escaped with double quotes. – Steve Buzonas Jun 30 '14 at 04:34
  • 2
    @SteveBuzonas, you just pwned that guy with your RFC. – devinbost Sep 24 '14 at 19:26
10

There are many methods to convert an array to comma separated list

1. Using array#join

From MDN

The join() method joins all elements of an array (or an array-like object) into a string.

The code

var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");

Snippet

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr.join(",");
console.log(arr);

2. Using array#toString

From MDN

The toString() method returns a string representing the specified array and its elements.

The code

var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();

Snippet

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr.toString();
console.log(arr);

3. Add []+ before array or +[] after an array

The []+ or +[] will convert it into a string

Proof

([]+[] === [].toString())

will output true

console.log([]+[] === [].toString());
var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;

Snippet

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = []+arr;
console.log(arr);

Also

var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr + [];
console.log(arr);
Sagar V
  • 12,158
  • 7
  • 41
  • 68
9

Use the built-in Array.toString method

var arr = ['one', 'two', 'three'];
arr.toString();  // 'one,two,three'

MDN on Array.toString()

Avijit Gupta
  • 5,676
  • 3
  • 20
  • 35
4

Safe way for string that contains separator (comma)

let arr = ["Hello, there", "How's there", 'the "best"']
let csv = arr.map(e => JSON.stringify(e)).join(",")
console.log(csv)

result

"Hello, there","How's there","the \\"best\\""
roel
  • 1,640
  • 14
  • 13
3

I usually find myself needing something that also skips the value if that value is null or undefined, etc.

So here is the solution that works for me:

// Example 1
const arr1 = ['apple', null, 'banana', '', undefined, 'pear'];
const commaSeparated1 = arr1.filter(item => item).join(', ');
console.log(commaSeparated1); // 'apple, banana, pear'

// Example 2
const arr2 = [null, 'apple'];
const commaSeparated2 = arr2.filter(item => item).join(', ');
console.log(commaSeparated2); // 'apple'

Most of the solutions here would return ', apple' if my array would look like the one in my second example. That's why I prefer this solution.

knowbody
  • 8,106
  • 6
  • 45
  • 70
2

Papa Parse handles commas in values and other edge cases.

(Baby Parse for Node has been deprecated - you can now use Papa Parse in the Browser and in Node.)

Eg. (node)

const csvParser = require('papaparse'); // previously you might have used babyparse
var arr = [1,null,"a,b"] ;
var csv = csvParser.unparse([arr]) ;
console.log(csv) ;

1,,"a,b"

Bob
  • 1,589
  • 17
  • 25
2

As of Chrome 72, it's possible to use Intl.ListFormat:

const vehicles = ['Motorcycle', 'Bus', 'Car'];

const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log(formatter.format(vehicles));
// expected output: "Motorcycle, Bus, and Car"

const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });
console.log(formatter2.format(vehicles));
// expected output: "Motorcycle, Bus oder Car"

const formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });
console.log(formatter3.format(vehicles));
// expected output: "Motorcycle Bus Car"

Please note that this way is in its very earlier stage, so as of the date of posting this answer, expect incompatibility with older versions of Chrome and other browsers.

Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116
2
const arr = [1, 2, 3];
console.log(`${arr}`)
gildniy
  • 3,528
  • 1
  • 33
  • 23
1

Taking the initial code:

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

The initial answer of using the join function is ideal. One thing to consider would be the ultimate use of the string.

For using in some end textual display:

arr.join(",")
=> "Zero,One,Two"

For using in a URL for passing multiple values through in a (somewhat) RESTful manner:

arr.join("|")
=> "Zero|One|Two"

var url = 'http://www.yoursitehere.com/do/something/to/' + arr.join("|");
=> "http://www.yoursitehere.com/do/something/to/Zero|One|Two"

Of course, it all depends on the final use. Just keep the data source and use in mind and all will be right with the world.

E Roberts
  • 11
  • 3
1

Do you want to end it with an "and"?

For this situation, I created an npm module.

Try arrford:


Usage

const arrford = require('arrford');

arrford(['run', 'climb', 'jump!']);
//=> 'run, climb, and jump!'

arrford(['run', 'climb', 'jump!'], false);
//=> 'run, climb and jump!'

arrford(['run', 'climb!']);
//=> 'run and climb!'

arrford(['run!']);
//=> 'run!'


Install

npm install --save arrford


Read More

https://github.com/dawsonbotsford/arrford


Try it yourself

Tonic link

Dawson B
  • 1,224
  • 12
  • 16
1

I liked the solution at https://jsfiddle.net/rwone/qJUh2/ because it adds spaces after commas:

array = ["test","test2","test3"]
array = array.toString();
array = array.replace(/,/g, ", ");
alert(array);

Or, as suggested by @StackOverflaw in the comments:

array.join(', ');
Jaime Montoya
  • 6,915
  • 14
  • 67
  • 103
  • 1
    in one call: `arr.join(', ')`, which is actually faster (according to @Sameer comments), and also safer (does not mess with commas inside array values as would the RegExp on the resulting string). ;) – Stock Overflaw Aug 29 '18 at 16:02
  • @StockOverflaw Way better. Less code to do the same thing plus safer and faster. Thank you. – Jaime Montoya Aug 29 '18 at 16:25
1

here you can separate with any char and can take any property list with just foreach

let taskIds: string = '';    
this.checkedTaskList.forEach(res => {
  taskIds = taskIds + res.taskId.toString() + ','
});
if (taskIds) {
    taskIds.substring(0, taskIds.length - 1),**
}
Ali Akram
  • 39
  • 4
0

In case you have an array of objects but want a comma delimited string from one of the properties on the object.

var arr = [
    { Id: 1, Name: 'Item 1' },
    { Id: 2, Name: 'Item 2' },
    { Id: 3, Name: 'Item 3' }
];
var result = arr.map(i => { return i.Name; }).join(', ');
console.log(result); // 'Item 1, Item 2, Item 3'
Quiver
  • 1,351
  • 6
  • 33
  • 56
-1
var arr = ["Pro1", "Pro2", "Pro3"];
console.log(arr.join());// Pro1,Pro2,Pro3
console.log(arr.join(', '));// Pro1, Pro2, Pro3
Akash
  • 51
  • 7
-1
var array = ["Zero", "One", "Two"];
var s = array + [];
console.log(s); // => Zero,One,Two
alejandro
  • 2,799
  • 1
  • 17
  • 25
  • 1
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – kayess Jun 01 '17 at 09:43
-1

This solution also removes values such as " ":

const result = ['', null, 'foo', '  ', undefined, 'bar'].filter(el => {
  return Boolean(el) && el.trim() !== '';
}).join(', ');

console.log(result); // => foo, bar
Yorkshireman
  • 2,194
  • 1
  • 21
  • 36