Search code snippets, questions, articles...

Join array items and convert to string in javascript

We can use Array.join() method to join all the elements of the array and convert them to a string. By default, it will join the items with a comma seperator.
const names = ["Rick", "Grimes", "Carol", "Alicia"];

//Join with default sepearor ,
name_str_1 = names.join();
console.log(name_str_1);
// -> Rick,Grimes,Carol,Alicia

//Jon with space seperator
name_str_2 = names.join(" ");
console.log(name_str_2);
// -> Rick Grimes Carol Alicia
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

You can pass separator inside join() method if you want to join the array items other than comma operator. 

In the code snippet, we have an array named names that contain multiple items. We are joining those items using names.join() method.

Live Demo

Join items using Array.forEach() function

We cal also use Array.forEach() function to join the array items and create a list from them.

var arr = ["D", "e", "v", "s", "h", "e", "e", "t"];

result = ""

arr.forEach( item => result += item )

console.log(result);

Output

Devsheet

Live Demo of joining array items using Array.forEach

Was this helpful?
0 Comments