102

In Ruby I can do ('a'..'z').to_a to get ['a', 'b', 'c', 'd', ... 'z'].

Does JavaScript provide a similar construct?

1
  • 6
    No, you need to create your own. Commented Jul 6, 2014 at 15:52

28 Answers 28

176

Personally I think the best is:

alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');

Concise, effective, legible, and simple!

EDIT: I have decided, that since my answer is receiving a fair amount of attention to add the functionality to choose specific ranges of letters.

function to_a(c1 = 'a', c2 = 'z') {
    a = 'abcdefghijklmnopqrstuvwxyz'.split('');
    return (a.slice(a.indexOf(c1), a.indexOf(c2) + 1)); 
}

console.log(to_a('b', 'h'));

Sign up to request clarification or add additional context in comments.

7 Comments

How would you accommodate ('m'..'p').to_a, ('A'..'F').to_a or ('1'..'5').to_a?
@PaulS. I don't know ruby, but I will try to port it over some time today.
Little extra: If you are really lazy, you could just drag your finger across each row on your keyboard (qwertyuiop...), then use the sort method to put the letters back in order.
To get all characters in UPPER CASE: const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('').map((c) => c.toUpperCase());
What would you say the expected output of to_a('A', 'z'); is? Or to_a('α', 'ω') @MichaelLonghurst ? Also @sonlexqt if you order your ops the other way around you save a lot of CPU; 'abcdefghijklmnopqrstuvwxyz'.toUpperCase().split('')
|
94

A short ES6 version:

const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
console.log(alphabet);

Comments

69

You can easily make a function to do this for you if you'll need it a lot

function genCharArray(charA, charZ) {
    var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
    for (; i <= j; ++i) {
        a.push(String.fromCharCode(i));
    }
    return a;
}
console.log(genCharArray('a', 'z')); // ["a", ..., "z"]

6 Comments

charCodeAt(0) for i and j?
@f1f5 to get the Unicode encoding value of the first character of each argument.
I think this is the way to do it. It could also be made generic by testing the type of the arguments and returning an appropriate range, like numbers for example.
So just happened to come across this, but actually typing out a function that returns the array of character literals has less characters than this function. See my codepen: codepen.io/jarodsmk/pen/NYaaxx
thanks, some useful demo for small childs mrswed.github.io/Russian_alphabet_for_color with all letters
|
64

In case anyone came here looking for something they can hard-code, here you go:

["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"]

3 Comments

Literally the same length as nonhardcoded solutions.
Haha, exactly what I want. 😄
Easiest dozens of upvotes ever🙂
47
new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );

Use 97 instead of 65 to get the lowercase letters.

1 Comment

could use 'A'.charCodeAt(0) to remove a magic number (at a small cost to performance)
26

By using ES6 spread operator you could do something like this:

let alphabet = [...Array(26).keys()].map(i => String.fromCharCode(i + 97));

1 Comment

Use 65 instead of 97 to get the uppercase letters.
18

A lot of these answers either use an array of characters or String.fromCharCode, I propose a slightly different method that takes advantage of letters in base36:

[...Array(26)].map((e,i)=>(i+10).toString(36))

The advantage of this one is purely code golf, it uses fewer characters than the others.

5 Comments

I haven't seen this before. Can you explain why .toString(36) makes it alphabets.
@RotimiBest Base 10 numbers use 10 possible characters (0-9) to represent each digit. Base 36 numbers numbers use 0-9 plus A-Z to represent all their digits. .toString(36) converts a base 10 number into base 36. This code creates an array of numbers 10-35 and converts them each to base 36. 10->A, 11->B ... 35->Z.
Can you do this with upper case letters?
@Timo Append .toUpperCase() after toString(36)...
Nice new solution, that 99% have to google when they see it ^^
17

I saw an answer I loved above which was the hardcoded list of the english alphabets but it was in lower case only and I needed upper case too so I decided to modify it in case someone else needs it:

const lowerAlph = ["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"];

const upperCaseAlp = ["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"];

2 Comments

no, you made code block instead of inline code, which doesn't have a scollbar, triple click to select line includes your variable definition, which somebody might not want. Lower case is already there above so I put a uppercase one ['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'] (copied from yours, and somehow you have different code style)
@Valen Fixed the inline code for better readability. Thanks for the observation.
9

in case if you need a hard-coded array of the alphabet, but with a less typing. an alternative solution of what mentioned above.

var arr = "abcdefghijklmnopqrstuvwxyz".split("");

will output an array like this

/* ["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"] */

1 Comment

7

Magic

[...8337503854730415241050377135811259267835n.toString(36)]

// chrome & firefox
let a1 = [...8337503854730415241050377135811259267835n.toString(36)];

console.log(a1);


// version working on all browsers (without using BigInt)
let a2 = [...[37713647386641440,2196679683172530,53605115].map(x=>x.toString(36)).join``];  

console.log(a2);

4 Comments

+1 thanks. Kamil, would like to know more about how this works, because it does.
@MatsdeSwart puzzle hint: focus on 36
Same question here: for Base 36, there is no uppercase, because 36 is needed for 26 lowercases + numbers, right?
See the comments on this earlier answer for hints.
5

Try

[...Array(26)].map((x,i)=>String.fromCharCode(i + 97))

let alphabet = [...Array(26)].map((x,i)=>String.fromCharCode(i + 97));

console.log(alphabet);

Update

As you noticed in comments this idea was already used in this answer (I missed it) - but this answer is shorter so treat it as size improvement of that older answer

Comments

4

To add to @Sherwin Ablaña Dapito solution ( I like to have some hints in answers)

  • 65 is start for upper Alphabet, 26 is number of chars in Alphabet
  • fill() method changes all elements in an array to a static value (1), in-place.
  • map() is applied to every elem, creates a new array and has a func as arg.
  • => arrow function expression, can be written as function (i){ return i+ 65;}
  • _ in map: ignore param (placeholder value, no value here) and use second = index
  • String.fromcharcode is self explanatory

new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );

Comments

2

Generate Character List with one-liner

const charList = (a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[...Array(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));

console.log("from A to G", charList('A', 'G'));
console.log("from A to Z with step/delta of 2", charList('A', 'Z', 2));
console.log("reverse order from Z to P", charList('Z', 'P', -1));
console.log("from 0 to 5", charList('0', '5', 1));
console.log("from 9 to 5", charList('9', '5', -1));
console.log("from 0 to 8 with step 2", charList('0', '8', 2));
console.log("from α to ω", charList('α', 'ω'));
console.log("Hindi characters from क to ह", charList('क', 'ह'));
console.log("Russian characters from А to Я", charList('А', 'Я'));

For TypeScript
const charList = (p: string, q: string, d = 1) => {
  const a = p.charCodeAt(0),
    z = q.charCodeAt(0);
  return [...Array(Math.floor((z - a) / d) + 1)].map((_, i) =>
    String.fromCharCode(a + i * d)
  );
};

Comments

2

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + (i * step));

let alpha  = range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map((x) => String.fromCharCode(x));
// ["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"]
console.log(alpha);

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.
1

Just for fun, then you can define a getter on the Array prototype:

Object.defineProperty(Array.prototype, 'to_a', {
  get: function () {
    const start = this[0].charCodeAt(0);
    const end = this[1].charCodeAt(0);
    return Array.from(Array(end - start + 1).keys()).map(n => String.fromCharCode(start + n));
  }
});

Which makes it possible to do something like:

['a', 'z'].to_a; // [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", ..., "z" ]

3 Comments

Sebastian Simon you might like this solution. Also if you prefer my implementation (stackoverflow.com/questions/24597634/…) then you can replace the implementation of this one with that one.
Also we could define this property for the String prototype (instead of the Array one) and then do 'az'.to_a.
For production code, would not recommend extending the prototype of a built-in unless you're writing a polyfill to the ecmascript spec (in which case why not also open source it). You could end up with unexpected behaviour with other people's code
1

Here is a quick one-liner

No dependencies!

Array.from(Array(26)).map((e, i) => i + 65).map((x) => String.fromCharCode(x));

console.log(Array.from(Array(26)).map((e, i) => i + 65).map((x) => String.fromCharCode(x)));

Comments

1

Try this

let name = ''

for(let i=0; i<26; i++){
  name+=(i+10).toString(36)
}

console.log(name.split(''))

Comments

1

//using map 1 line code

let alphabet =[...Array(26)].map( (_,i) => String.fromCharCode(65+i) )

// using array for inserting A-Z

let newArray = []
for(var i = 0; i<26 ; i++){
  newArray.push(String.fromCharCode(65+i))
}

// using array for inserting a-z

let newArray = []
for(var i = 0`enter code here`; i<26 ; i++){
  newArray.push(String.fromCharCode(65+i).toLowerCase())
}

//using split

 let a = 'abcdefghijklmnopqrstuvwxyz'.split('');

Comments

1

Here's another way:

const chars = [];
for (let i=65; i<=65+25; i++){
  chars.push(String.fromCharCode(i));
}

console.log(chars, Array.isArray((chars )));

1 Comment

Use 97 and 97 + 25 to get an array of lowercase letters
1

I like this way.

[...Array(26)].map((_, i) => String.fromCharCode(i + 97))
// ['a', 'b',..., 'z']

more example

for (const data of [
  [...Array(10)].map((_, i) => i), // 0-9
  [...Array(26)].map((_, i) => String.fromCharCode(i + 65)), // A-Z
  [...Array(26)].map((_, i) => String.fromCharCode(i + 97)), // a-z
  [...Array(26)].map((_, i) => `${String.fromCharCode(i + 97)}${String.fromCharCode(i + 65)}` ).join(""), // aAbB...zZ
]) {
  console.log(JSON.stringify(data)) // This is for those who have hardcoded requirements.
}

1 Comment

You can use 'a'.charCodeAt(0) instead of the "magic number" 97 or 'A'.charCodeAt(0) for uppercase
0

Using JavaScript's Array.from syntax allows you to create an array and perform a mapping function on each of the array elements. Create a new array of length 26 and on each element set the value equal to the string obtained from the char code of the index of the current element plus the ascii magic number.

const alphabet = Array.from(Array(26), (e, i) => String.fromCharCode(i + 97));

Again, 97 may be interchanged with 65 for an uppercase alphabet.

The array may also be initialized with values using the object's keys method rather than utilising the index of the map

const alphabet = Array.from(Array(26).keys(), i => String.fromCharCode(i + 97));

1 Comment

No need to pass in an array, you only need an object with a length property. { length: 26 }
0
const ALPHA = Array.from({ length: 26 }, (_, i) => String.fromCharCode('a'.charCodeAt(0) + i)); // ['a', 'b', ...'z']

I believe the above code is more idiomatic. Short enough to be an inline code. You don't have to remember the charCode of your start letter and configurable to retrieve subsets of the alphabet by simply controlling the length and start letter e.g

Array.from({ length: 3 }, (_, i) => String.fromCharCode('x'.charCodeAt(0) + i)) // ['x', 'y', 'z]

Comments

0

I like to use this:

[...Array(26).keys()].map(n => n + 'a'.codePointAt(0)).map(ch => String.fromCharCode(ch))

Comments

0

See result

function getAsciiToString(from, total) {
  let count = 0;
  let asciiLetters = "";

  while (count < total) {
    const asciiDigit = from.charCodeAt(0) + count;
    asciiLetters += String.fromCharCode(asciiDigit);
    count++;
  }

  return asciiLetters;
}

console.log(getAsciiToString("a", 26));
console.log(getAsciiToString("A", 26));
console.log(getAsciiToString("0", 10));

Comments

0

This is the most efficient as there are no wasted temporary arrays.

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

console.log(alphabetLowerCase);

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

console.log(alphabetUpperCase);

Comments

0

We can do the following:

var result = ''

for (
    let character = 'a'

    ; character <= 'z'

    ; character = String.fromCharCode(
        character.charCodeAt() + 1
    )
)
    result += character

console.log(result)

Here result is already an array-like object, but if you would need it as an actual array you could do the following instead:

var result = []

for (
    let character = 'a'

    ; character <= 'z'

    ; character = String.fromCharCode(
        character.charCodeAt() + 1
    )
)
    result.push(character)

console.log(result)

3 Comments

Looks good logically and can be easily adjusted to work over any sequence of chars. Would be interesting to see memory, CPU and garbage collection implications of the different ways to build the output 🤔
You can save yourself a decode if you store the numeric value, but that would then be very similar to my answer
Yes, my goal was to literally write what I want to do as much as possible. Yes, basically your answer is that, which is a little faster.
0

I stumbled over this old post and found another solution via a javascript generator:

function* upperCaseAlphabet() {
  let index = 0;
  while (index < 26) {
    yield String.fromCharCode(65 + index);
    index++;
  }
  return
}

Used like this:

for (const letter of upperCaseAlphabet()) {
  console.log(letter);
}

console.log(...upperCaseAlphabet());

1 Comment

The return isn't strictly necessary. But I like to know when my function is actually done in an explicit way.
-2

No Javascript or Jquery doesnot provide anything like that. You have to create your own array.

You may try like this:

var alpha = ["a","b","c",....];

or better try like this:

var index = 97;
$("#parent .number").each(function(i) {
    $(this).html(String.fromCharCode(index++));
});

DEMO

7 Comments

I really think he probably wants something a little more automated than manually typing out the entire alphabet. Seems clear from the question that he already knows how to create an array.
@cookiemonster:- Updated my answer with a demo! Hope that helps OP!
Something a little more directly relevant to the question might be to use $.map() to create an Array. $.map(Array(26), function(_, i) { return String.fromCharCode(i + 97); }) jsfiddle.net/agKrz/18
@cookie post as answer. I like that best :)
@f1f5: I think the answer posted by Paul S is much better. I was mostly just providing an alternative that didn't rely on DOM elements.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.