Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate an array of alphabet in jQuery?

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?

like image 251
MrPizzaFace Avatar asked Jul 06 '14 15:07

MrPizzaFace


People also ask

How do you turn a string into an array in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.

What is array from in JS?

The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.


3 Answers

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'));
like image 197
Michael Longhurst Avatar answered Nov 14 '22 05:11

Michael Longhurst


A short ES6 version:

const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
console.log(alphabet);
like image 41
HenningCash Avatar answered Nov 14 '22 05:11

HenningCash


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"]
like image 63
Paul S. Avatar answered Nov 14 '22 06:11

Paul S.