Gabriel
Gabriel

Reputation: 109

Javascript - construct an array with elements repeating from a string

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)

Upvotes: 3

Views: 56

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386600

You could get an array of a padded string.

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

console.log(result);   

Upvotes: 2

Rajesh
Rajesh

Reputation: 24925

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))

Upvotes: 1

Nick Parsons
Nick Parsons

Reputation: 50759

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)

Upvotes: 5

Related Questions