How to generate an array of alphabet in jQuery?

JavascriptJquery

Javascript Problem Overview


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

Do jQuery or Javascript provide a similar construct?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

A short ES6 version:

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Use 97 instead of 65 to get the lowercase letters.

Solution 6 - Javascript

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

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Solution 15 - Javascript

Try this

let name = ''

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

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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

Solution 18 - Javascript

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]

Solution 19 - Javascript

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

Solution 20 - Javascript

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

Solution 21 - Javascript

I like to use this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMrPizzaFaceView Question on Stackoverflow
Solution 1 - JavascriptMichael LonghurstView Answer on Stackoverflow
Solution 2 - JavascriptHenningCashView Answer on Stackoverflow
Solution 3 - JavascriptPaul S.View Answer on Stackoverflow
Solution 4 - JavascriptBryce JohnsonView Answer on Stackoverflow
Solution 5 - JavascriptmendezcodeView Answer on Stackoverflow
Solution 6 - JavascriptSherwin Ablaña DapitoView Answer on Stackoverflow
Solution 7 - Javascriptrotimi-bestView Answer on Stackoverflow
Solution 8 - JavascriptSyd LambertView Answer on Stackoverflow
Solution 9 - JavascriptsamehanwarView Answer on Stackoverflow
Solution 10 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 11 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 12 - JavascriptTimoView Answer on Stackoverflow
Solution 13 - JavascriptnkitkuView Answer on Stackoverflow
Solution 14 - JavascriptCoder Gautam YTView Answer on Stackoverflow
Solution 15 - JavascriptRidwan AjibolaView Answer on Stackoverflow
Solution 16 - JavascriptRahul TripathiView Answer on Stackoverflow
Solution 17 - JavascriptTkrZView Answer on Stackoverflow
Solution 18 - JavascriptelayiraView Answer on Stackoverflow
Solution 19 - JavascriptAndreas LouvView Answer on Stackoverflow
Solution 20 - JavascriptNeeraj JerauldView Answer on Stackoverflow
Solution 21 - JavascriptBart LouwersView Answer on Stackoverflow