2

I am trying to iterate over the original string 3 times. The result I get is: ["a","b","c","d",undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined]

The correct result should be: ["a", "b", "c", "d", "a", "b", "c", "d", "a", "b", "c", "d"]

function makeCopies (str, howmany) {
  let newCopy = [];
   for(let i = 0; i <  str.length * howmany; i++) {
   newCopy.push(str[i])
   } 
return newCopy;
}

console.log(makeCopies("abcd", 3))

I have tried many variations but nothing works, this is the closest I got.

Miloš Leng
  • 101
  • 1
  • 10

6 Answers6

4

JavaScript has a repeat Method on Strings. You can just use "abcd".repeat(3) and you will get "abcdabcdabcd". If you really want an array of the chars, you can spread the string into an array with [..."abcd".repeat(3)].

Thomas Kay
  • 229
  • 1
  • 2
  • 5
2

Javascript has a nice utility for this String.prototype.repeat. You can then split it on every character if an array is what you want.

console.log("abcd".repeat(3).split(""))
Jonathan Hamel
  • 1,393
  • 13
  • 18
1

The length of the array is becoming 12 when you multiply str.length * howmany, and when it gets further than the fourth value it can't find anything and so becomes undefined.

A solution is you can wrap the main loop in another loop which will run howmany times.

function makeCopies (str, howmany) {
   let newCopy = [];
   for (let i = 0; i < howmany; i++) {
       for(let j = 0; j <  str.length; j++) {
            newCopy.push(str[j])
        } 
    }
    return newCopy;
  }

  console.log(makeCopies("abcd", 3))
Justin Feakes
  • 380
  • 1
  • 7
1

const makeCopies = (string, count) => new Array(count).join(string).split('');

console.log(makeCopies('abcd', 4))
a.mola
  • 3,883
  • 7
  • 23
1

Why don’t you use repeat() ?

const res = "abc".repeat(3); // abcabcabc

If you need it as array, you can:

res.split(""); // ["a", "b", "c", ...]
ikos23
  • 4,879
  • 10
  • 41
  • 60
0

You are iterating outside the bounds of original string

str[i]; // i <  str.length * howmany;

Try create two cycles instead:

for(let i = 0; i < howmany; i++) {
  for(let j = 0; j < str.length; j++) {
    newCopy.push(str[j])
  }
}
peter
  • 583
  • 2
  • 11