2

In ruby I can use the following code to generate an array of strings from a to z:

alphabet = ('a'..'z').to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

Is there a similar function call in Javascript?

Richard Jarram
  • 899
  • 11
  • 22

2 Answers2

3

Unfortunately, ECMAScript does not have a Range in its standard library. However, what you can do, is to use the Array.from factory function to construct an Array using a mapping function.

Something like this:

const alphabet = Array.from({ length: 26 }, (_, i) => i + 97).map(String.fromCharCode);

Or, without magic numbers:

const charCodeOfA = "a".charCodeAt(0),                //=>  97
    charCodeOfZ = "z".charCodeAt(0),                  //=> 122
    lengthOfAlphabet = charCodeOfZ - charCodeOfA + 1, //=>  26

    alphabet = Array.from({ length: lengthOfAlphabet }, (_, i) => i + charCodeOfA).
        map(String.fromCharCode);

In future versions of ECMAScript, it would be nice to use do expressions to avoid polluting the namespace with those temporary helper variables:

const alphabet = do {
    const charCodeOfA = "a".charCodeAt(0),                //=>  97
        charCodeOfZ = "z".charCodeAt(0),                  //=> 122
        lengthOfAlphabet = charCodeOfZ - charCodeOfA + 1; //=>  26

    Array.from({ length: lengthOfAlphabet }, (_, i) => i + charCodeOfA).
        map(String.fromCharCode)
}
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
1

The easy way to do that is

var alphabet =[];
for(var i = "a".charCodeAt(0); i <= "z".charCodeAt(0); i++) {
        alphabet.push(String.fromCharCode(i))

}
  • 1
    Great idea! You could swap out the `...charCodeAt...` with the char values (97 & 122) for a shorter and more performant solution. – my Year Of Code May 24 '19 at 01:50