I'm doing an exercise (self-study) in which I must have an array that has a string being inserted into it n times.
I have this
var splitTxt = [];
for(i=0 ; i<n ; i++)
{
splitTxt += text.split('');
}
text
being the string given in the function. I've looked around but I only ever see advice on how to add characters and other strings etc. to the ends of arrays.
Adding split normally produces the desired result, however, when looping it like this, i get a comma in every index in the array. What is happening here, and how do I do it properly?
I can do this:
for(i=0 ; i<n ; i++)
{
splitTxt.push(text.split(''));
}
But that produces a nested array, not desired.
I can also do this:
var secondChar = [].concat(...Array(n).fill(text.split('')));
But, again, nested array. I like this one though, using the array constructor to mess with it, very clever. An answer given by @CertainPerformance here
EDIT: Sorry, I wasn't clear enough. I'd like to split it into the array multiple times like so:
var text = "hello there!";
n = 3;
desired result: ["h","e","l","l","o"," ","t","h","e","r","e","!","h","e","l","l","o"," ","t","h","e","r","e","!","h","e","l","l","o"," ","t","h","e","r","e","!"]