Languages

JavaScript - convert array of strings to comma separated string

5 points
Asked by:
Marcin
2544

Is there easy way to convert array of string to comma separated string in JavaScript?

I mean without using for loop and string concatination.

I know I can do this like this:

// ONLINE-RUNNER:browser;

var arr = ['en', 'de', 'pl'];
var text = '';

for (var i = 0; i < arr.length; i++) {
    text += arr[i];

    if (i !== arr.length - 1) {
        text += ',';
    }
}

console.log(text); // en,de,pl

Output:

en,de,pl

Is there easier way to do this?

1 answers
3 points
Answered by:
Marcin
2544

The best and quickes way it to use array.join(",") method.

Quick example with 1 liner solution:

// ONLINE-RUNNER:browser;

var arr = ['en', 'de', 'pl'];
var text = arr.join(",");

console.log(text); // en,de,pl

Output:

en,de,pl

 

0 comments Add comment
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join