For example, we have the below string array :
[‘one’, ‘two’, ‘three’, ‘four’]
Our program will join these words and print the below string :
i.e. it will join the array elements using a custom separator.
We can create one string variable, iterate through the array and join each element to this string variable to create the final string.
Let’s write the code :
let givenArray = ['one','two','three'] let result = '' givenArray.forEach(item => result = result + item + ',') result = result.slice(0, -1) console.log(result)
Explanation of this program :
- givenArray is the given array of strings.
- result is the final result. It is a string initialised with empty value.
- We are iterating through the array elements one by one using forEach. For each element, we are adding it with result with a comma at end.
- The final result will add one comma at the end of the string. We are using slice to remove the last comma.
It will print the below output :
Array.join() method is used to join array elements with a custom separator. I would recommend you to use this method than the above one because it is concise and efficient. The above example uses one loop and slice to get the result but using join, you can get the result in just one line :
let givenArray = ['one','two','three'] let result = givenArray.join(',') console.log(result)
That’s it. It will print :
Even, if you don’t specify the separator to join, it will add comma as the default separator :
let givenArray = ['one','two','three'] let result = givenArray.join() console.log(result)
It will print the same result.