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?

3

3 Answers 3

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)]);
Sign up to request clarification or add additional context in comments.

1 Comment

This will give error for Range(9,1). This case is also not handled
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.

6 Comments

OP needs 1-8 if input with (1,9)
@AnkitAgarwal, updated.
This will give error for Range(9,1). This case is also not handled
@AnkitAgarwal, for start > end I returns just an empty array.
Yes, it seems good now
|
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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.