Languages

JavaScript - convert array of strings to comma separated string

5 points
Asked by:
Iona
265

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?

2 answers
3 points
Answered by:
Iona
265

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
0 points
Answered by:
Iona
265

As mentioned above in the first answer, the easiest way for just converting an array to a string is to use the join method but I wanted to show you another and newer method which provides more flexibility since you can write your own custom logic that will be executed for each element inside the array. Using the reduce method you can manipulate each element as desired.

// ONLINE-RUNNER:browser;

const arr = ['en', 'de', 'pl'];
const text = arr.reduce((acc, cur) => `${acc},${cur}`);

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

 

0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join