Create an Array of Alphabet characters in JavaScript with this simple trick

image

Initializing an array is simple concept, but make it into alphabet is different thing. Perhaps for many people this article is useless. But, i’m not seeing anybody write this article yet. So i write this one. The first concept is we need to initialize an array that fulfilled with the number of integer. It can be done using some method just like below.

ES6

Array.from(Array(10).keys());
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Spread Operator

[...Array(10).keys()];
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

map function

Array.from({ length: 10 }, (_, i) => i + 1);
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

From this point of view, our purpose is to make an array that consist all alphabet character. Instead of writing things that will take too much time like this

const alphabet = [
  "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",
];

I have solution to make that thing without writing all of the character. The concept is just the same with making array that fulfilled with integer just like above. Here i using map function too.

const alpha = Array.from(Array(26)).map((e, i) => i + 65);
const alphabet = alpha.map((x) => String.fromCharCode(x));
console.log(alphabet);

As you can see, i declared an array named alpha, and fulfill it with integer that represent charCode from string and filling it with the length of 26. After that, in second line, by using map function i change all the number from every element in alpha become string and save it into variable name alphabet. So, the output of that is 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",
];

How easy isn’t it? I hope you enjoy this article.

Thanks

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics