1

Is there a way to create an Integer range?

In other languages, I can use Range(1, 9) to create [1, 2, ... 8] easily.

Is there a simple way to create the list in JavaScript?

smali
  • 4,687
  • 7
  • 38
  • 60
sof-03
  • 2,255
  • 4
  • 15
  • 33

3 Answers3

2
 const range = (start, end) => Array.from({length: end - start}, (_, i) => start + i);

 console.log(range(1,5));

That creates an array with the indexes. If you need it in a loop, an iterator might be better:

 function* range(start, end = Infinity) {
   for(let i = start; i < end; i++)
     yield i;
 }

Which can be used as:

 for(const v of range(1, 10))
    console.log(v);

You can also turn an iterator into an array easily:

 console.log([...range(0, 10)]);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

Is there a simple way to create the list in JavaScript?

No, but you can create your own solution using ES features like map and spread syntax.

var range = (start, end) => start < end ? [...Array(end - start)].map((_, i) => start + i) : [];
console.log(range(1,9));

Also, returns an empty array for case when start is greater than end.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

You can create a reusable function called Range and loop over the start and end values. You can further add a if condition that ensures that the start value is always less than the end value.

function Range(start, end){
  var rangeArray = [];
  if(start < end){
    for(var i=start; i<end; i++){
      rangeArray.push(i);
    }
  }
  return rangeArray;
};

console.log(Range(1,9));
console.log(Range(2,9));
console.log(Range(5,12));
console.log(Range(16,12));
console.log(Range(30,12));
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62