In Ruby I can do ('a'..'z').to_a
to get ['a', 'b', 'c', 'd', ... 'z']
.
Does JavaScript provide a similar construct?
In Ruby I can do ('a'..'z').to_a
to get ['a', 'b', 'c', 'd', ... 'z']
.
Does JavaScript provide a similar construct?
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'));
A short ES6 version:
const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
console.log(alphabet);
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"]
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"]
new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );
Use 97 instead of 65 to get the lowercase letters.
By using ES6 spread operator you could do something like this:
let alphabet = [...Array(26).keys()].map(i => String.fromCharCode(i + 97));
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"];
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.
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"] */
[...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);
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
To add to @Sherwin Ablaña Dapito solution ( I like to have some hints in answers)
function (i){ return i+ 65;}
String.fromcharcode
is self explanatorynew Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );
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)
);
};
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" ]
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)));
Try this
let name = ''
for(let i=0; i<26; i++){
name+=(i+10).toString(36)
}
console.log(name.split(''))
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);
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 )));
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));
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]
//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('');
I like to use this:
[...Array(26).keys()].map(n => n + 'a'.codePointAt(0)).map(ch => String.fromCharCode(ch))
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));
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);
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)
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']
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++));
});