Receive a String in this format: "1-10" and create an array with the amount of numbers in the range

68 views Asked by At

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.

3

There are 3 answers

4
kyun On BEST ANSWER

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);  

2
Anurag Singh Bisht On

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);
}

0
Jonas Wilms On

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...]