Convert An Array Into A Comma-Separated List In JavaScript
How do you convert an array into a comma-separated list when coding in JavaScript?
There are two different ways to do this using either the toString()
or join()
native JavaScript methods.
In this article, we'll cover how to use both of these methods in your code.
Let's get into it!
Method 1 - toString()
We'll go over the toString()
method first, which will result in the formation of a string concatenated by commas.
Here's what the code looks like:
const array = ["Zero", "One", "Two", "Three", "Four"]
array.toString() // "Zero,One,Two,Three,Four"
Given the array of strings, the toString()
method converts it into one string separated by commas.
You can also transform the array into a string by implicitly calling toString()
with these methods:
""+array // "Zero,One,Two,Three,Four"
`${array}` // "Zero,One,Two,Three,Four"
Using those methods, you'll get the same result as explicitly calling toString()
.
Method 2 - join()
The second method we'll go over is the join()
method, which creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.
Here's what the code looks like:
const array = ["Zero", "One", "Two", "Three", "Four"]
array.join() // "Zero,One,Two,Three,Four"
This method returns the same string as the toString()
method from the last section.
You can also customize the spacing between each item in the new string and what types of characters to use:
array.join(" ") // "Zero One Two Three Four"
array.join(", ") // "Zero, One, Two, Three, Four"
array.join(" + ") // "Zero + One + Two + Three + Four"
array.join("") // ZeroOneTwoThreeFour
As you can see, each example returns a new string with no commas, no spacing, commas with spaces, or +
symbols. You can replace those values with anything you'd like.
Both the toString()
and join()
method is widely supported amongst different browsers and versions.
Thanks for reading and happy coding!