Herb Caudill
Herb Caudill

Reputation: 49952

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

Upvotes: 552

Views: 663215

Answers (23)

aleEspinosaM
aleEspinosaM

Reputation: 444

you can use

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

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

Upvotes: 2

Dev 404
Dev 404

Reputation: 1587

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'

Upvotes: 0

roel
roel

Reputation: 1660

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

Upvotes: 4

Ali Akram
Ali Akram

Reputation: 39

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),**
}

Upvotes: 1

jfk
jfk

Reputation: 5287

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

Upvotes: 41

gildniy
gildniy

Reputation: 3903

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

Upvotes: 2

Bob
Bob

Reputation: 1679

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"

Upvotes: 2

Yorkshireman
Yorkshireman

Reputation: 2343

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

Upvotes: -1

Eliya Cohen
Eliya Cohen

Reputation: 11458

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.

Upvotes: 3

Jaime Montoya
Jaime Montoya

Reputation: 7701

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

Upvotes: 1

Sagar V
Sagar V

Reputation: 12478

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

Upvotes: 10

knowbody
knowbody

Reputation: 8276

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.

Upvotes: 3

alejandro
alejandro

Reputation: 2847

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

Upvotes: -1

Andrew Downes
Andrew Downes

Reputation: 557

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

Upvotes: 22

Akash
Akash

Reputation: 51

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

Upvotes: -1

skibulk
skibulk

Reputation: 3188

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

Upvotes: 14

Dawson B
Dawson B

Reputation: 1495

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

Upvotes: 1

Wayne
Wayne

Reputation: 39878

The Array.prototype.join() method:

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

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

Upvotes: 995

Avijit Gupta
Avijit Gupta

Reputation: 5756

Use the built-in Array.toString method

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

MDN on Array.toString()

Upvotes: 9

E Roberts
E Roberts

Reputation: 11

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.

Upvotes: 1

mpen
mpen

Reputation: 282825

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.

Upvotes: 11

Ateş G&#246;ral
Ateş G&#246;ral

Reputation: 140032

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.

Upvotes: 121

Sergey Ilinsky
Sergey Ilinsky

Reputation: 31535

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.

Upvotes: 30

Related Questions