2

Is there a shorter more efficient way of doing this? it seems a little hefty and I just want to know if it can be condensed?

 var y = []

  for(let i=0;i < word.length;++i){
    if(word[i] == "A"|| word[i] == "a"){
      y.push(0)
    }
    else if(word[i] == "B"|| word[i] == "b"){
      y.push(1);
    }
    else if(word[i] == "C"|| word[i] == "c"){
      y.push(2);
    }
    else if(word[i] == "D"|| word[i] == "d"){
      y.push(3);
    }
and so on..


  return(y);
}
El CC
  • 77
  • 2
  • 9
  • You may find it useful to use characters instead of strings when indexing. That way, you can use the following to condense the entire if/else down to a few lines: https://stackoverflow.com/questions/94037/convert-character-to-ascii-code-in-javascript – Andrew Fan Dec 05 '18 at 02:55
  • Hi; is your question answered? You have not marked an accepted answer so please let us know if there is anything else you need. – Matt Dec 05 '18 at 19:50

2 Answers2

6

One option is to use an array of characters, then use .indexOf to find the index of the character:

const word = 'bBac';
const chars = ['a', 'b', 'c', 'd'];

const y = [...word].map(char => chars.indexOf(char.toLowerCase()))
console.log(y);
// return y;

For slightly better efficiency, instead of .indexOf (which is O(N)), use a Map (O(1)):

const word = 'bBac';
const charMap = new Map([
  ['a', 0],
  ['b', 1],
  ['c', 2],
  ['d', 3]
]);

const y = [...word].map(char => charMap.get(char.toLowerCase()))
console.log(y);
// return y;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You can make use of the ASCII values, which eliminates the need to maintain a structure containing all the letters:

let letterValue = word[i].toUpperCase().charCodeAt(0) - 65;  // 65 represents the offset of the alphabet in the ASCII table
if (letterValue >= 0 && letterValue <= 25) {  // Check that the value is A-Z
  y.push(letterValue);
}
Matt
  • 2,953
  • 3
  • 27
  • 46