-4

How to Receive a String in this format: "1-10" and create an array with the amount of numbers in the range. Print the array to screen using a for loop.

I.E - "1-5" received so they array will be: {1,2,3,4,5}

create for workflow with vCenter orchestrator.

mplungjan
  • 169,008
  • 28
  • 173
  • 236

3 Answers3

2

You can split the string into array and then iterate in a loop to get the iteration.

let str = "1-5";
str = str.split('-');
for(let i = parseInt(str[0]); i<=parseInt(str[1]); i++) {
  console.log(i);
}
Anurag Singh Bisht
  • 2,683
  • 4
  • 20
  • 26
  • 1
    Your loop will be more efficient if you parse the end number first, instead of each time you check the bounds. – mjk Sep 03 '17 at 13:43
  • Yes sure.. Should leave some things for the person asking the questions to. But yes doing it first will be more efficient. – Anurag Singh Bisht Sep 03 '17 at 13:45
1

You may use some cool ES6:

Array.range = function(s){
 const [start,end] = s.split("-");
 return Array.from({length:start-end}).map((_,i)=>i+ +start);
};

Usable like this:

Array.range("1-10") //[1,2,3...]
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

var input = "1-10";  //SAMPE INPUT DATA.
var foo = input.split("-");  //PASRING INPUT DATA.
var answer = []; 
for(var i = foo[0]; i<= foo[1]; i++){
   answer.push(parseInt(i));  //MAKE AN ARRAY.
}
console.log(answer);  
kyun
  • 9,710
  • 9
  • 31
  • 66