Are you getting the requirements of converting a javascript array to string without commas? If yes, then this article is for you. Generally when we convert array to string we use some delimiters to separate the values. But in some cases we do not want delimiters. For example, characters array can be used to join values to create words. Here we do not want any delimiter between characters.
This is a fun article because we are going to take one step further. I will show you how you can join values of a jumbled array using a pattern.
Let’s see how we can do this with code.
Code Example
We are defining an array of characters which doesn’t make any sense right now. Because this is jumbled. Can you figure out what it is saying? Don’t worry we will create a code to solve it.
const myArray = ['T','i','o','s','n',' ','y','i',' ','r','S','o','t','n','a','m','r','a','k','n',' '];
First, I will show you the code to join javascript array values to string without commas and without using pattern.
console.log(myArray.join('')); // Output: Tiosn yi rSotnamrakn .
You may also like this (opens in new tab) –
Now let’s move to the fun part. We will convert it to a meaningful string using pattern to solve it. In our array myArray
, if we pick alternate characters and join them, then it will lead to something good.
const arrayToStringUsingPattern = (myArray, pattern, cycles) => { var myArrayString = ''; for(var i=0; i<cycles; i++){ for(var j=i; j<myArray.length; j += pattern){ myArrayString += myArray[j]; } } return myArrayString; } console.log(arrayToStringUsingPattern(myArray, 2, 2)); //Output: Tony Stark is ironman
In this code, we have declared a function arrayToStringUsingPattern
. It accepts 3 parameters. First one is our input array, myArray
. Second is pattern
which decides the value to pick. So, if pattern is 2, then we will pick every odd or even indexed values. Third is cycles
which decides how many times we want to run the loop on input array.
If pattern
is 2 and cycles
is 1, then it will run like this –
[‘T‘,’i’,’o‘,’s’,’n‘,’ ‘,’y‘,’i’,‘ ‘,’r’,’S‘,’o’,’t‘,’n’,’a‘,’m’,’r‘,’a’,’k‘,’n’,‘ ‘]
If pattern
is 2 and cycles
are 2, then it will run like this –
In 1st cycle –
[‘T‘,’i’,’o‘,’s’,’n‘,’ ‘,’y‘,’i’,‘ ‘,’r’,’S‘,’o’,’t‘,’n’,’a‘,’m’,’r‘,’a’,’k‘,’n’,‘ ‘]
In 2nd cycle –
[‘T’,’i‘,’o’,’s‘,’n’,‘ ‘,’y’,’i‘,’ ‘,’r‘,’S’,’o‘,’t’,’n‘,’a’,’m‘,’r’,’a‘,’k’,’n‘,’ ‘]
If you change the pattern
and cycles
values then output will be unexpected.
Live Demo
What people reads after –