Jay Jenkins
Jay Jenkins

Reputation: 423

How do I split a string into an array multiple times without it being nested? JavaScript

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","!"]

Upvotes: 1

Views: 663

Answers (3)

tremor
tremor

Reputation: 3186

Wanted to see if I could do this without using repeat and split, and here is what I came up with.

function mapx(text, x) {
    var myArray = [];
    for (var y = 0; y < x; y++) { 
        myArray = myArray.concat(Array.prototype.map.call(text, i => i));
    }
    return myArray;
}

var result = mapx('hello there!', 3);

console.log(result);

array.map and array.concat are pretty well supported in browsers. You could use .split instead .map - in fact I believe split benchmarks faster than map in small arrays. When objects get larger map has an advantage.

Upvotes: 1

V. Sambor
V. Sambor

Reputation: 13389

After seeing you edit, the simplest way to achieve what you want can be done in a single line:

console.log('hello there!'.repeat(3).split(''));

Upvotes: 2

cyr_x
cyr_x

Reputation: 14257

Based on your example, just repeat the text n times and then split it:

function splitText(text, n) {
  return text.repeat(n).split('');
}

var result = splitText('hello there!', 3);
console.log(result);

Keep in mind that String.prototype.repeat isn't supported by older browsers, but it can be easily polyfilled.

Upvotes: 0

Related Questions