skip to Main Content

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


  1. 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.

    console.log([...'Alex'.toUpperCase()].map(i=>i.charCodeAt(0)-64))
    Login or Signup to reply.
  2. As I said in my comment, you should have wordformat being iterated over first, and then alphabet inside of that loop.

    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('');
    
      wordformat.map((letter, l) => {
        alphabet.map((word, i) => {
          if (word === letter) {
            result.push((i = 1 + i));
          }
        });
      });
    
      console.log(result);
    }
    
    replace('alex');
    Login or Signup to reply.
  3. 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.

    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) {
      return word.split('')
        .map((letter)=> alphabet.indexOf(letter) + 1);
    }
    
    console.log(replace('alex')); // [  1,  12,  5,  24 ]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search