3

Suppose there is a string aba and a limit 5. How can i create an array with elements repeating from the string till the limit is reached ?

e.g. string = "aba" and limit = 5 will give new array ["a","b","a","a","b"]

As of now, my array fills with all characters then blank strings are repeated for the left indexes.

function repeatedString(s, n) {
  let arr = [];
  for (let i = 0; i < n; i++) {
    let char = s.charAt(i);
    arr.push(char);
  }
  console.log(arr);
}

repeatedString("aba", 5)

3 Answers 3

5

Your code is almost there. You just need to let your index you use in .charAt() wrap back to 0 when you reach the length of the string. This can be done using the remainder operator (%) with the length of the string like so:

function repeatedString(s, n) {
  let arr = [];
  for (let i = 0; i < n; i++) {
    let char = s.charAt(i % s.length);
    arr.push(char);
  }
  console.log(arr);
}

repeatedString("aba", 5)

Sign up to request clarification or add additional context in comments.

Comments

2

You could get an array of a padded string.

var string = 'aba',
    limit = 5,
    result = Array.from(''.padStart(limit, string));

console.log(result);   

Comments

1

You can use string functions for this:

  • Calculate the times given string needs to be repeated.
  • Repeat the string and extract n length string from it
  • Split this string by individual characters

function repeatedString(s, n) {
  const repeatCount = Math.ceil(n/s.length);
  return s.repeat(repeatCount).slice(0, n).split('');
}

console.log(repeatedString("aba", 5))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.