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

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

This question is related to javascript

The answer is


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

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.


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


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

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.


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

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.


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

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.


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

_x000D_
_x000D_
const vehicles = ['Motorcycle', 'Bus', 'Car'];_x000D_
_x000D_
const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });_x000D_
console.log(formatter.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus, and Car"_x000D_
_x000D_
const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });_x000D_
console.log(formatter2.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus oder Car"_x000D_
_x000D_
const formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });_x000D_
console.log(formatter3.format(vehicles));_x000D_
// expected output: "Motorcycle Bus Car"
_x000D_
_x000D_
_x000D_

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.


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"


Simple Array

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

Array of Objects with a particular attributes as comma separated.

_x000D_
_x000D_
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);
_x000D_
_x000D_
_x000D_


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

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.


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

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

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

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

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

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

Proof

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

will output true

_x000D_
_x000D_
console.log([]+[] === [].toString());
_x000D_
_x000D_
_x000D_

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

Snippet

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

Also

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

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


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.


Use the built-in Array.toString method

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

MDN on Array.toString()


Simple Array

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

Array of Objects with a particular attributes as comma separated.

_x000D_
_x000D_
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);
_x000D_
_x000D_
_x000D_


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.


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.


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

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

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"


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

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

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

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

_x000D_
_x000D_
const vehicles = ['Motorcycle', 'Bus', 'Car'];_x000D_
_x000D_
const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });_x000D_
console.log(formatter.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus, and Car"_x000D_
_x000D_
const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });_x000D_
console.log(formatter2.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus oder Car"_x000D_
_x000D_
const formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });_x000D_
console.log(formatter3.format(vehicles));_x000D_
// expected output: "Motorcycle Bus Car"
_x000D_
_x000D_
_x000D_

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.


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

Use the built-in Array.toString method

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

MDN on Array.toString()


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


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.


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.


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.


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

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

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

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

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

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

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

Proof

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

will output true

_x000D_
_x000D_
console.log([]+[] === [].toString());
_x000D_
_x000D_
_x000D_

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

Snippet

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

Also

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

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


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.


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.


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

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