Search code examples
javascriptascii

JS function of representing array elements in ASCII


function translateInWord(mas){
  mas = [].concat(...mas);
  for (let i = 0; i < mas.length; i++){
    mas[i] = String.fromCharCode(mas[i]);
  }
  return mas;
}
console.log(translateInWord([[6,8,13],[5,3,0]]));

I want the program to show me every letter in ASCII from the array 'mas` (that is, it should turn out ['G','I','N','F','D','A'])


Solution

  • You are using a 0-indexed representation of the alphabet (0 -> A, ..., 25 -> Z).

    fromCharCode() is taking UTF-16 code units as parameters.

    If you look at an UTF-16 table, the decimal representation of A is 65 and the following 25 code units are corresponding to the other capital letters of the alphabet up to Z.

    So you just need to add 65 to mas[i] to get its corresponding letter :

    function translateInWord(mas){
      mas = [].concat(...mas);
      for (let i = 0; i < mas.length; i++){
        mas[i] = String.fromCharCode(mas[i] + 65);
      }
      return mas;
    }
    console.log(translateInWord([[6,8,13],[5,3,0]]));