There are few ways you can convert an array to a string: with or without a separator, with custom logic, or as a string literal.
Some of them are:
1. Using array.toString() .
2. Using array.join() .
4. Using array.reduce() .
5. Using JSON.stringify() .
1. Using array.toString()
This method joins each element in the array with a comma:
2. Using array.join()
Unlike the array.toString() method, you can use the array.join() method to convert the array into a string with or without commas. It accepts one argument:
You can use the separator argument to specify a string to separate each element. This argument is optional. If you don't specify the separator argument, it will join the elements with a comma.
3. Using loops
The array.toString() and array.join() methods work well, but aren't suitable for custom logic. Let's say that you need to only add a separator after a certain value in the array. In this case the first two methods won't work. Instead, you can use a loop to define custom logic:
Here, we are looping through the elements in the array using a for loop. We check to see if the element is equal to 'b' . If it is, we append that element with a separator. Otherwise we append the element without the separator.
Метод toString() возвращает строковое представление указанного массива и его элементов.
Объект Array переопределяет метод toString объекта Object . Для объектов класса Array , метод toString соединяет массив и возвращает одну строку, содержащую каждый элемент массива, разделённый запятыми. Например, следующий код создаёт массив и использует метод toString для преобразования массива в строку.
js array to string and converting an array to a string in general
I have wrote a post on the subject of the to string method of an object in general before, however in todays post I think I will take a moment to write about this subject when it comes to arrays alone. The to string method of an array will work okay when it comes to an array of primitives, however it will often fall short of expectations when it comes to an array of objects. When it comes to converting a complex array of objects into a string format it is often called for to create a custom helper function, or class prototype method to do so. It is also possible to create a custom to string method for an array, and when making a custom class that makes use of an array it is general a good idea to have a to string method as part of the prototype object.
1 — Basic examples of the array to string method
Source code is on Github
1.1 — An Array of primitives
If I am dealing with a simple array of primitives and I want a string value of the array I can often just call the to string method. The default to string method of the array prototype will often give me what I want when it comes to this, however often I might still want to use an alternative method to create a string value from an array.
1.2 — An Array of Objects
When I am dealing with an array of objects this is often when the to string method will fall short, or at least the default to string method of the array prototype object at least. The main reason why is because I will end up with the string object Object for each object in the resulting string. This will just abut never be the kind of result that I will want when it comes to creating a string from an array of objects. So then I will need to do something else other than use the to string method, or create a custom to string method for the object, or the prototype of the object that I am using.
1.3 — Using array map first to work with an Array of Objects
One way to address the problem that I run into with the to string method is to just use a method like array map to create a custom array or privative values first. I can then just call the to string method of off the instance of the new array that is created from array map.
1.4 — Creating a custom to string method
Another option would be to create a custom to string method. When doing this it is possible to monkey patch the array prototype with a custom array prototype, but generally that would not be a good idea, as it would effect this functionally everywhere in a page. However one thing that can be done is to create an own property of a single array instance without mutating the state of the prototype object of the Array class.
1.5 — Creating a Class
When it comes to making my own class that is separate from the array prototype I can of course create my own to string method for this new class of object, without worry about touching any built in prototype. Having a to string method is generally a good idea when it comes to creating any kind of class object, as it allows be th create whatever the standard string format of my custom class of object should be. While I am at it I should also make sure to create a value of method for the class also and use that to define what a number value should be for the class of object.
2 — The array join method, and many other array prototype methods for creating a string from an array
The to string method of an array might not always be the best option for creating a string from an array. Another major option for this sort of thing would be the join method of the array prototype. This method works by just calling the method off of an instance of an array, and by default it works just like the to string method of the array prototype. However there is one additional argument that can be given to the array join method that can be used to change what the separator character should be between elements when creating a string.
However there is not just the join method of the array prototype but many other useful methods in the array prototype as well as other prototypes such a the String prototype that can be used to help with the process of creating string from arrays. So in this example I will be going over a few examples of the array join method, but I will also be going over a few of the other array prototype methods that I might call first before ending with the join method.
2.1 — Basic array join method example
To start out with the array join method there is once again just quickly calling the method alone with say a simple array of numbers. When this is the case the result is the same as the built in to string method, at least when the join method is not given any argument at least. The first argument of the array join method can be used to set what it is that should be between each element when creating a string. By default this value is a comma, but I can give a space, dash, or an empty string in the event that I want there to be noting between each element in the string that is returned by the array join method.
2.2 — Joining a collection of objects into a string
A problem similar to that of just using a built in to string method will also come up when it comes to creating a string from an array of objects. The thing about this though is that I almost never just use the array join method by itself, there are many other useful methods in the array prototype after all. For example I can use the array map method to create a new array of strings rather than objects where each substring is formated the way I want an object to be represent first. AFter that I can then call the array join method off of the new array that is returned by the array map method.
2.3 — The filter method
I might want to do more then just create a new array of sub string values from an an array using map before converting to a string. For example I might want to filter out a while bunch of elements in an array that I will not want in the final string first. One way to go about doing this would be to use the array filter method first. this filter method like the map method will create and return a new array rather than mutating one in place like some other methods in the array prototype. However one major difference with filter compared to map is that the aim is not to just cerate a new array with the same length, but a lower length that is only the elements that I want from a source array. After I call filter off of a source array, I can then use the map, and join methods to create my final string value that I want.
2.4 — The sort method
Yet another thing that I might want to do with an array is to sort a collection of elements, in the array prototype there is the array sort method that can be done to sort array elements by some kind of property, or any kind of conditions defined in a sort method. For example say that I once again have a source array with mixed values some of which do not apply for what I want, so they must be filtered out. Then the objects that remain have a money value to which I wan to sort by for each object.
2.5 — For Each
There is then just simply using the array for each method to loop over each element and then just concatenate what I want to a string value. Some might regard this as a crude way to go about doing this sort of thing, but in many simple coding examples and projects the end result will end up working out just fine. There may be some draw backs to using the for each method, but if something works fine for me in my own project then that is the case, and I can then move on. I think the best thing to keep in mind is that this is not the only tool in the toolbox then it comes to array prototype methods and, many of the other options are very useful when it comes to parsing threw a source array.
2.6 — The reduce method
Maybe one of the best options to work with would be the array reduce method actually when it comes to prototype methods that are useful for creating a string primitive from an array. This is a method that is often used to create a sum from an array, however it can also very much be used to create a string primitive also. For example If I have an array of numbers and I want to create a string from this array of numbers I can call the reduce method off of the array, and pass a method that will be used to preform the reduction as the first argument, followed by a starting value for the accumulator value that I will be using in the reduction function, in this case it would be a string value.
In the body of the reduction function the first argument is the accumulator value that I started with the second argument of the reduce method. So then I just need to concatenate the current element value that I want that is the second argument in the reducer function and then return that. The return value will then be the value for the accumulation in the next call of the reducer function and so forth.
This reduce method is sure worth looking into more, and it is called for to work out some custom examples just for the sake of playing around with it more if you have not done so all ready. The value that the array is reduced to can be a number also, or any kind of object as well if one feels they need to do that.
3 — Using JSON to create a string from an array
Another way to go about converting an array, or any object to a string would be to use JSON to do so. There are two main methods that come to mind with JSON the parse method, and the stringify method. It is the stringify method that can be used to covert an array to a string, and do so in a way in which all the data of the nested objects will be in a string form. There are some draw backs though depending on what the intension is when it comes to converting an array to a string this way. The main thing about JSON is that it is an example of a data serialization language. What I mean by this is that is is a standard way to convert objects to a from that can then be transmitted over a network, or stored in a file, rather then exiting in a more workable from.
3.1 — Basic array to string example Uisng JSON
To create a string from an array using JSON I just call the JSON.stringify method to do so, and pass the array that I want to convert to a string in JSON from. The returned value will then be a string that is a JSON from of that array.
That will be about it at least when it comes to creating a JSON string from an array at least anyway. There is also the subject of how to go about converting back to an object for example. There is also maybe some things to be aware of when it comes to certain things that have to do with objects created with custom constructors that will be elements of objects in the array, or nested objects in such objects.
3.2 — Basic JSON string to object example
When it comes to converting a JSON string back to an object that I can then work with I will want to use the JSON.parse method. For this I just call the JSON parse method and pass the JSON string as the first and argument and if all goes well the return value of this method will then be the original array.
There is a whole lot more to this though when it comes to crating a string from an array this way. For example in some cases I might end up passing a malformed JSON string to the parse method that will result in an error. So then it would make sense to call this method in the body of a try catch statement. There are also some problems that will come up when it comes to using custom constrictors which is one reason why I might want to use a reviver function when calling this parse method.
4 — Conclusion
The array to string method is the default way to go about creating a string value from an array. However it is not the end all solution for this sort of thing, there are a number of other options to be aware of. Also in some cases it is possible that a custom solution will need to be made for create a string value of an object, in the form of some kind of helper function, or a custom to string method that is used in place of array to string one way or another.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Arrays are a powerful feature of any language. They let you house multiple pieces of information easily. They will maintain the order of items being added and can even be sorted. In modern web browsers, they even handle auto-magically converting themselves into human readable strings.
Even with the modern niceties, it’s still good to know how to convert an array to a string for those times when you need to massage an array into another format, or want to do something more than simply comma separating the values (the default behavior).
No special tools required. You can hack along in either your web browser’s console or using the Node.js REPL. The commands utilized are baked into the Array Object’s prototype.
To string, or Not to String.
If you were to run the following in your browser:
You would receive an alert with the message 1,2,3 without any additional work on your part. If all you need to do is display the contents of an array in this format, this can get you pretty far. This even works when referencing array objects inside of template literals.
Under the hood, the array items are being joined together as a string, using the comma , character as the delimiter. It’s the same as running either of the following:
Both result in the same 1,2,3 string.
In fact, that’s all that the .toString() method can do for us. It accepts no parameters so it’s usefulness is fairly limited.
While it’s default behavior (without any passed parameters) is the same as .toString() , the .join() method is significantly more robust.
Let’s say you wanted to include a space after the comma when creating your string, you can tell .join() the exact string to use:
Prefer to have each array item on it’s own line? Pass in a new line character:
Working with HTML and want to use those breaks instead?
Want HTML breaks AND new lines. Okay, you get the idea.
The .join() method accepts an optional parameter that lets you define the separator character or characters you’d like to use to join the array items together.
Speaking of HTML
One of my favorite .join() tricks, before template literals and JSX made it extremely easy to work with multiple line blocks of markup, was to use .join() to assemble an array of HTML tags into a string:
Passing in an empty string to .join() simply joins the array items without any additional characters.
Still pretty handy for dealing with multiple line strings and/or markup when you don’t have access to some of the more modern syntax options.
Even if all you’re trying to do is display a comma separated list of array items to a user, you can still benefit from using the .join() method. It gives you more control over the output which will make things easier to read for your users.
Working with a back-end server that doesn’t understand arrays being passed-in? Join your array items into a single value and you’re good to go!
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.