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

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

The Array.prototype.join() method:

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

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

Use the built-in Array.toString method

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

MDN on Array.toString()

Solution 10 - Javascript

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.

Solution 11 - Javascript

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"

Solution 12 - Javascript

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

Solution 13 - Javascript

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.

Solution 14 - Javascript

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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.

Solution 17 - Javascript

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

Solution 18 - Javascript

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

Solution 19 - Javascript

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

Solution 20 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHerb CaudillView Question on Stackoverflow
Solution 1 - JavascriptWayneView Answer on Stackoverflow
Solution 2 - JavascriptAtes GoralView Answer on Stackoverflow
Solution 3 - JavascriptSergey IlinskyView Answer on Stackoverflow
Solution 4 - JavascriptAndrew DownesView Answer on Stackoverflow
Solution 5 - JavascriptJafar KaruthedathView Answer on Stackoverflow
Solution 6 - JavascriptskibulkView Answer on Stackoverflow
Solution 7 - JavascriptmpenView Answer on Stackoverflow
Solution 8 - JavascriptSagar VView Answer on Stackoverflow
Solution 9 - JavascriptAvijit GuptaView Answer on Stackoverflow
Solution 10 - JavascriptknowbodyView Answer on Stackoverflow
Solution 11 - JavascriptBobView Answer on Stackoverflow
Solution 12 - JavascriptJaime MontoyaView Answer on Stackoverflow
Solution 13 - JavascriptEliya CohenView Answer on Stackoverflow
Solution 14 - JavascriptgildniyView Answer on Stackoverflow
Solution 15 - JavascriptAli AkramView Answer on Stackoverflow
Solution 16 - JavascriptE RobertsView Answer on Stackoverflow
Solution 17 - JavascriptDawson BView Answer on Stackoverflow
Solution 18 - JavascriptAkashView Answer on Stackoverflow
Solution 19 - JavascriptalejandroView Answer on Stackoverflow
Solution 20 - JavascriptYorkshiremanView Answer on Stackoverflow