- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ]
- Related Articles
- Sum of all the non-repeating elements of an array JavaScript
- Code to construct an object from a string in JavaScript
- Finding array intersection and including repeating elements in JavaScript
- Construct an array from GCDs of consecutive elements in given array in C++
- Sorting array of exactly three unique repeating elements in JavaScript
- Building an array from a string in JavaScript
- Repeating letter string - JavaScript
- Detecting the first non-repeating string in Array in JavaScript
- Counting below / par elements from an array - JavaScript
- Repeating only even numbers inside an array in JavaScript
- Product of non-repeating (distinct) elements in an Array in C++
- JavaScript - How to pick random elements from an array?
- Construct an array from XOR of all elements of array except element at same index in C++
- How to filter an array from all elements of another array – JavaScript?
- C# program to create a List with elements from an array

Advertisements