555

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

1
  • 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 Commented May 30, 2018 at 6:34

23 Answers 23

1000

The Array.prototype.join() method:

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

document.write(arr.join(", "));

Sign up to request clarification or add additional context in comments.

8 Comments

@Mark: true enough but I need to concatenate list of IDs, no chance of commas or other special chars
@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: 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: 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 - 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?
|
121

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.

4 Comments

There is also the shorter (but less clear) arr + ''
array.toString does the job without space after comma. With array.join you are flexible.
performance of toString() and join(",") is roughly equivalent as of Apr 2018
This is the perfect answer. To get CSV of an array we can just use console.log(arr) or like you said, casting it as string automatically makes it CSV.
42

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

Comments

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.

1 Comment

In most cases, toString is actually slower than array join. Lookie here: jsperf.com/tostring-join
23

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');
}

Comments

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");
    };
}

Comments

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.

4 Comments

Noooooooooo! Tempted to downvote. What if the quotes should be escaped with backslashes?! They need to be variable. ;)
@JoshuaBurns wikipedia 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 ;)
Actually there is an RFC, tools.ietf.org/rfc/rfc4180.txt, and that is correct double quotes should be escaped with double quotes.
@SteveBuzonas, you just pwned that guy with your RFC.
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);

Comments

9

Use the built-in Array.toString method

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

MDN on Array.toString()

Comments

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\\""

Comments

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.

Comments

3

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.

Comments

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"

Comments

2
const arr = [1, 2, 3];
console.log(`${arr}`)

Comments

2

you can use

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

const formatter = new Intl.ListFormat('en', {
  style: 'short',
  type: 'conjunction',
});

Comments

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.

Comments

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

Comments

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(', ');

2 Comments

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). ;)
@StockOverflaw Way better. Less code to do the same thing plus safer and faster. Thank you.
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),**
}

Comments

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'

Comments

-1
var arr = ["Pro1", "Pro2", "Pro3"];
console.log(arr.join());// Pro1,Pro2,Pro3
console.log(arr.join(', '));// Pro1, Pro2, Pro3

Comments

-1
var array = ["Zero", "One", "Two"];
var s = array + [];
console.log(s); // => Zero,One,Two

1 Comment

While this code snippet may solve the question, including an explanation 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!
-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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.