- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Building an array from a string in JavaScript
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.
e.g. string = "string" and limit = 8 will give new array
const arr = ["s","t","r","i","n",“g”,“s”,”t”]
Example
Let’s write the code for this function −
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 −
[ '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
- Building a frequency object from an array JavaScript
- JavaScript construct an array with elements repeating from a string
- Building frequency map of all the elements in an array JavaScript
- Find unique and biggest string values from an array in JavaScript
- Converting string to an array in JavaScript
- How to parse a string from a JavaScript array?
- Find the Smallest element from a string array in JavaScript
- Search from an array of objects via array of string to get array of objects in JavaScript
- Ordering string in an array according to a number in the string JavaScript
- Finding unique string in an array in JavaScript
- Constructing array from string unique characters in JavaScript
- Removing comments from array of string in JavaScript
- Removing an element from an Array in Javascript
- Find the shortest string in an array - JavaScript
- Shuffling string based on an array in JavaScript

Advertisements