JavaScript construct an array with elements repeating from a string


We have to write a function that creates an array with elements repeating from the string till the limit is reached. Suppose there is a string ‘aba’ and a limit 5 −

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

Let’s write the code for this function −

Example

const string = 'Hello';
const limit = 15;
const createStringArray = (string, limit) => {
   const arr = [];
   for(let i = 0; i < limit; i++){
      const index = i % string.length;
      arr.push(string[index]);
   };
   return arr;
};
console.log(createStringArray(string, limit));
console.log(createStringArray('California', 5));
console.log(createStringArray('California', 25));

Output

The output in the console will be −

[
   'H', 'e', 'l', 'l',
   'o', 'H', 'e', 'l',
   'l', 'o', 'H', 'e',
   'l', 'l', 'o'
]
[ 'C', 'a', 'l', 'i', 'f' ]
[
   'C', 'a', 'l', 'i', 'f', 'o',
   'r', 'n', 'i', 'a', 'C', 'a',
   'l', 'i', 'f', 'o', 'r', 'n',
   'i', 'a', 'C', 'a', 'l', 'i',
   'f'
]

Updated on: 24-Aug-2020

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements