In Ruby I can do (\'a\'..\'z\').to_a
and to get [\'a\', \'b\', \'c\', \'d\', ... \'z\']
.
Do jQuery or Javascript provide a similar construc
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"]
Try
[...Array(26)].map((x,i)=>String.fromCharCode(i + 97))
let alphabet = [...Array(26)].map((x,i)=>String.fromCharCode(i + 97));
console.log(alphabet);
By using ES6 spread operator you could do something like this:
let alphabet = [...Array(26).keys()].map(i => String.fromCharCode(i + 97));
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"] */
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" ]
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('А', 'Я'));
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)
);
};