Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the 1-based index of a character in alphabets using JavaScript
We are required to write a JavaScript function that takes in a lowercase English alphabet character. Our function should return the character's 1-based index in the alphabets.
Problem
Given a lowercase English alphabet character, we need to find its position in the alphabet where 'a' = 1, 'b' = 2, 'c' = 3, and so on.
Method 1: Using String indexOf()
We can create a string containing all alphabets and use indexOf() to find the position:
const char = 'j';
const findCharIndex = (char = '') => {
const legend = ' abcdefghijklmnopqrstuvwxyz';
if(!char || !legend.includes(char) || char.length !== 1){
return -1;
};
return legend.indexOf(char);
};
console.log(findCharIndex(char));
10
Method 2: Using charCodeAt()
A more efficient approach uses ASCII values. The character 'a' has ASCII value 97, so we subtract 96 to get 1-based indexing:
const findCharIndexASCII = (char) => {
if (!char || char.length !== 1 || char < 'a' || char > 'z') {
return -1;
}
return char.charCodeAt(0) - 96;
};
console.log(findCharIndexASCII('a')); // 1
console.log(findCharIndexASCII('j')); // 10
console.log(findCharIndexASCII('z')); // 26
1 10 26
Method 3: Using Alphabet Array
We can also use an array and indexOf():
const findCharIndexArray = (char) => {
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'];
const index = alphabet.indexOf(char);
return index === -1 ? -1 : index + 1;
};
console.log(findCharIndexArray('f')); // 6
console.log(findCharIndexArray('m')); // 13
6 13
Comparison
| Method | Performance | Memory Usage | Readability |
|---|---|---|---|
| String indexOf() | Medium | Low | Good |
| charCodeAt() | Fastest | Lowest | Excellent |
| Array indexOf() | Slowest | Highest | Good |
Conclusion
The charCodeAt() method is the most efficient approach for finding alphabet positions. It uses ASCII arithmetic and provides O(1) time complexity with minimal memory usage.
