user2727195
user2727195

Reputation: 7330

How to split an array into single quotes and comma separated list in javascript

for instance if i have an array in javascript

var productIds = ["abc", "xyz", "123"]; //having string elements 

my desired output is not only to comma separate the array but surround each element with quotes.

'abc', 'xyz', '123'

I can do up to join, productIds.join(', ') but how to surround with quotes?

Upvotes: 3

Views: 12639

Answers (2)

Joe
Joe

Reputation: 15802

Add the quotes into the join and then wrap the resulting string in quotes as well. No need to add any extra overhead when it can be done more efficiently and be more readable.

"'" + myArray.join("', '") + "'";

The only case where this fails is with an empty array, so you can just test length in that case (the brackets aren't necessary, they're just for readability again):

myArray.length ? ( "'" + myArray.join("', '") + "'" ) : '';

Upvotes: 13

Pointy
Pointy

Reputation: 413702

You can use .map():

var quotedIds = productIds.map(function(id) { return "'" + id + "'"; }).join(", ");

The .map() function is available in newer browsers; if you need your code to work in an older browser, you can either include a shim or else simply implement that as a simple loop:

var quotedIds = [];
for (var i = 0; i < productIds.length; ++i)
  quotedIds.push("'" + productIds[i] + "'");
quotedIds = quotedIds.join(", ");

Upvotes: 7

Related Questions