JavaScript: Convert String to Title CaseHow to convert a JavaScript array to a comma-separated list?

How can I easily turn a JavaScript array into a comma-separated list? I have a one-dimensional array of strings in JavaScript, and I want to convert it into a comma-separated list using Javascript join array with comma. Is there a simple way to do this using garden-variety JavaScript (or jQuery)? I know how to manually iterate through the array and concatenate the strings, but I’m looking for a more straightforward method.

The simplest way to convert an array to a comma-separated string is by using the join() method. It’s super intuitive and works seamlessly for this purpose. You just specify the delimiter (in this case, a comma), and it does the rest for you. Here’s how it looks:

const arr = ['apple', 'banana', 'cherry'];
const result = arr.join(','); // 'apple,banana,cherry'

I’ve found this method to be quite efficient for everyday tasks.

Absolutely, Priyanka! To add on to that, you might want to consider how to handle any empty or undefined elements in your array. Using filter() before calling join() can help you clean up the array by removing any falsy values, like null, undefined, or empty strings. This way, your final result stays neat. Check it out:

const arr = ['apple', null, 'banana', undefined, 'cherry'];
const result = arr.filter(Boolean).join(','); // 'apple,banana,cherry'

This approach ensures your javascript join array with comma method works flawlessly, even with less-than-ideal data.

Great point, Building on that, if you want a bit more control over how your comma-separated list looks—like adding a space after each comma—you can opt for the reduce() method. It gives you a more customizable solution. Here’s an example of how you can implement it:

const arr = ['apple', 'banana', 'cherry'];
const result = arr.reduce((acc, curr) => acc ? acc + ', ' + curr : curr, ''); // 'apple, banana, cherry'

This way, you can format your output exactly how you like it while still using the javascript join array with comma concept as a foundation.