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
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.
In Javascript, the Array.join() function is used to join the elements of an array into a string. The string is created by concatenating the elements of the array, separated by a specified separator string. If no separator is specified, a comma is used by default.
Syntax
Array.join(separator)
Steps to create a string from array items using join() function
Code example
const arr = ["H", "el", "l", "o"];
console.log(arr.join(''));
// -> Hello
We can also use For loop to join the array items and generate a String from them if we do not want to use any function like Array.join(). To join the String from Array items:
const arr = ["H", "el", "l", "o"];
var result_str = '';
for (var i = 0; i < arr.length; i++) {
result_str += arr[i];
}
console.log(result_str);
Output
Hello
In the above code example, we have defined an array - arr. We have also created a string variable called result_str that contains an empty string.
Then, we initiated a For loop on the array - arr and in each iteration, we are adding array item to the result_str variable.
After that, we are printing the final result from the result_str variable to the console window.
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
The above code example will loop through the array and add each item to the result string. The result will be logged to the console as a single string.
0 Comments