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?

3
  • JS does not support this natively, unfortunately Commented May 24, 2019 at 0:47
  • 1
    Note: in Ruby, you would normally not convert to an Array, but rather use the Range directly, since it is much more memory-efficient. Commented May 24, 2019 at 3:11
  • @JörgWMittag Thanks for the tip! Commented May 24, 2019 at 15:25

2 Answers 2

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

Comments

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 Comment

Great idea! You could swap out the ...charCodeAt... with the char values (97 & 122) for a shorter and more performant solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.