i just created a function to replace every letter with its position in the alphabet, but it is sorted in order of the alphabet. for example, if i type ‘Alex’ the positions should be (1, 12, 5, 24), but instead is returning (1, 5, 12, 24). what am i doing wrong?
this is my code:
let result = [];
let 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" ];
function replace(word) {
let wordformat = word.split('');
alphabet.map((letter, i) => {
wordformat.map((word, l) => {
if (word === letter) {
result.push((i = 1 + i));
}
});
});
console.log(result);
}
replace('alex');
EDIT: I made a mistake on what i expected from the output. It is already fixed.
3
Answers
Use the spread syntax to convert the uppercase version of the string into an array, and then map each uppercase letter to an ASCII character code. Then, subtract 64 to get to regular alphabetic order starting with A=1, because A has the ASCII code of 65.
As I said in my comment, you should have
wordformat
being iterated over first, and thenalphabet
inside of that loop.Here is a solution with
map()
that returns the result array.Also I use
indexOf()
to find the index of the letter in the array.