-2

can I please ask how to make a range in Javascript? For example if I need to print letters "A" to "E" or number 1 to 5. For example in Ruby it is simple double dot like this (1..5).

I tried this code but it gives error.

let letter = range("A", "E");
console.log(letter);

Thank You

sakmario
  • 43
  • 4
  • 9
    Does this answer your question? [Does JavaScript have a method like "range()" to generate a range within the supplied bounds?](https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp) – JohnnyJS Jan 02 '20 at 13:47
  • In my opinion this would be the most elegant answer: function range (start, end) { let out = []; for(var i = start.charCodeAt(0); i <= end.charCodeAt(0); i++) { out.push(String.fromCharCode(i)); } return out; } console.log(range('A', 'D')); – BRO_THOM Jan 02 '20 at 13:55
  • I favor the generator method, as it can be converted to an array easily `[...range(1,1000)]` but if the range is large, and we only need `for (i of range(1,10000) { ... }`, we don't need to create the big array if not needed to – nonopolarity Jan 02 '20 at 14:00

2 Answers2

0

For numbers you can use ES6 Array.from(), which works in everything these days except IE:

Shorter version:

Array.from({length: 20}, (x,i) => i);

Longer version:

Array.from(new Array(20), (x,i) => i)

which creates an array from 0 to 19 inclusive. This can be further shortened to one of these forms:

Array.from(Array(20).keys())
// or
[...Array(20).keys()]

Lower and upper bounds can be specified too, for example:

Array.from(new Array(20), (x,i) => i + *lowerBound*)

An article describing this in more detail: http://www.2ality.com/2014/05/es6-array-methods.html

John Sp
  • 66
  • 3
  • 13
0

Javascript doesn't include that feature, but you can use Lodash which is javascript library which include that feature, and It's only for number.

But you can create your self function which generate range of number and for letters

Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31