Reputation: 109
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
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
Reputation: 24925
You can use string functions for this:
n
length string from itfunction 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
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