87

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

Does JavaScript provide a similar construct?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
MrPizzaFace
  • 7,807
  • 15
  • 79
  • 123

27 Answers27

160

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'));
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
Michael Longhurst
  • 1,750
  • 2
  • 10
  • 11
  • How would you accommodate `('m'..'p').to_a`, `('A'..'F').to_a` or `('1'..'5').to_a`? – Paul S. Sep 03 '15 at 14:15
  • 1
    @PaulS. I don't know ruby, but I will try to port it over some time today. – Michael Longhurst Feb 02 '16 at 10:00
  • 18
    Little extra: If you are really lazy, you could just drag your finger across each row on your keyboard (qwertyuiop...), then use the [sort](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) method to put the letters back in order. – Michael Longhurst Jan 09 '17 at 12:56
  • To get all characters in UPPER CASE: `const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('').map((c) => c.toUpperCase());` – sonlexqt Mar 18 '17 at 20:33
  • 3
    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('')` – Paul S. Jul 26 '17 at 21:24
  • one big pitfall of this method is that it is subject to typo. And the person who verifies this code has to visually go through your `a` to `z`. If you loop through `a` to `z` and print out the result and it contains all characters from `a` to `z`, there cannot be any typo in that series of 26 alphabets – nonopolarity Aug 30 '17 at 14:48
  • @PaulS. you might like the following solution: - https://stackoverflow.com/questions/24597634/how-to-generate-an-array-of-the-alphabet/64599298#64599298 Also if you prefer my implementation (https://stackoverflow.com/questions/24597634/how-to-generate-an-array-of-the-alphabet/76410805#76410805) then you can replace the implementation of this one with that one. – Erik Engi Jun 06 '23 at 02:20
81

A short ES6 version:

const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
console.log(alphabet);
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
HenningCash
  • 2,030
  • 18
  • 17
66

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"]
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
Paul S.
  • 64,864
  • 9
  • 122
  • 138
51

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

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
Bryce Johnson
  • 6,689
  • 6
  • 40
  • 51
41
new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );

Use 97 instead of 65 to get the lowercase letters.

mendezcode
  • 857
  • 8
  • 7
  • 4
    could use `'A'.charCodeAt(0)` to remove a magic number (at a small cost to performance) – alex Mar 02 '18 at 11:12
23

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

let alphabet = [...Array(26).keys()].map(i => String.fromCharCode(i + 97));
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"];

rotimi-best
  • 1,852
  • 18
  • 29
  • 1
    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 May 19 '19 at 18:35
  • 1
    @Valen Fixed the inline code for better readability. Thanks for the observation. – rotimi-best May 19 '19 at 20:02
13

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.

Syd Lambert
  • 1,415
  • 14
  • 16
  • I haven't seen this before. Can you explain why `.toString(36)` makes it alphabets. – rotimi-best Feb 06 '19 at 07:25
  • 1
    @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. – Syd Lambert Feb 10 '19 at 02:56
  • Can you do this with upper case letters? – Timo Jan 28 '21 at 07:24
  • 3
    @Timo Append `.toUpperCase()` after `toString(36)`... – Heretic Monkey Jan 28 '21 at 21:05
  • Nice new solution, that 99% have to google when they see it ^^ – GarfieldKlon Jun 23 '23 at 12:36
8

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"] */
samehanwar
  • 3,280
  • 2
  • 23
  • 26
6

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);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
4

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

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
3

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 ) );

Timo
  • 2,922
  • 3
  • 29
  • 28
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)
  );
};
nkitku
  • 4,779
  • 1
  • 31
  • 27
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" ]
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • Sebastian Simon you might like this solution. Also if you prefer my implementation (https://stackoverflow.com/questions/24597634/how-to-generate-an-array-of-the-alphabet/76410805#76410805) then you can replace the implementation of this one with that one. – Erik Engi Jun 06 '23 at 02:16
  • Also we could define this property for the `String` `prototype` (instead of the `Array` one) and then do `'az'.to_a`. – Erik Engi Jun 06 '23 at 11:04
  • 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 – Paul S. Jun 07 '23 at 07:52
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)));
Coder Gautam YT
  • 1,044
  • 7
  • 20
1

Try this

let name = ''

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

console.log(name.split(''))
Ridwan Ajibola
  • 873
  • 11
  • 16
1

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);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Aug 13 '22 at 09:14
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 )));
code
  • 5,690
  • 4
  • 17
  • 39
Mahmoud Magdy
  • 662
  • 10
  • 13
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));
TkrZ
  • 33
  • 1
  • 2
  • 5
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]
elayira
  • 1
  • 1
0

//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('');
0

I like to use this:

[...Array(26).keys()].map(n => n + 'a'.codePointAt(0)).map(ch => String.fromCharCode(ch))
Bart Louwers
  • 873
  • 9
  • 28
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));
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);
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
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)
Erik Engi
  • 402
  • 3
  • 10
  • 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 – Paul S. Jun 07 '23 at 07:46
  • You can save yourself a decode if you store the numeric value, but that would then be very similar to my answer – Paul S. Jun 07 '23 at 07:47
  • 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. – Erik Engi Jun 14 '23 at 05:19
0

var arr = ["C", "D", "X", "A", "B", "Z"]; console.log(arr.sort( function (a, b) { return a.localeCompare(b) })); // ['A', 'B', 'C', 'D', 'X', 'Z']

-1

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

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 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. – cookie monster Jul 06 '14 at 15:56
  • @cookiemonster:- Updated my answer with a demo! Hope that helps OP! – Rahul Tripathi Jul 06 '14 at 15:58
  • 1
    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); })` http://jsfiddle.net/agKrz/18/ – cookie monster Jul 06 '14 at 16:01
  • @cookie post as answer. I like that best :) – MrPizzaFace Jul 06 '14 at 16:02
  • @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. – cookie monster Jul 06 '14 at 16:03
  • the second code seems to be even longer than just write all the letters out, like this `var alpha = "abcdefghijklmnopqrstuvwxyz".split('');` – King King Jul 06 '14 at 16:08
  • why on the demo the very last character is "}" - a curly brace? – Vladyn Sep 27 '17 at 14:09