Replace a letter with its alphabet position

Question

This looked fairly straightforward to me when I started, but for some reason I'm getting an empty array everytime I try to run the result on codewars. I'm hoping you can help me identify what the problem is.

function alphabetPosition(text) {
  text.split(' ').join('');
  var chari = "";
  var arr = [];
  var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
  for(var i = 0; i < text.len; i++){
    chari = text.charAt(i).toLowerCase();
    if(alphabet.indexOf(chari) > -1){
      arr.push(alphabet.indexOf(chari));
    }
  }
  return arr;
}
console.log(alphabetPosition("Hello World"));

My idea is to get the text from the parameter then strip out the spaces. I made a variable for my empty array and make an alphabet string that I can later search through. In the for loop, i make each character lowercase, and if the character is found in the alphabet string, its position gets pushed into the array (arr). I appreciate your time.


Show source
| javascript   | arrays   | string   2017-01-02 13:01 9 Answers

Answers to Replace a letter with its alphabet position ( 9 )

  1. 2017-01-02 13:01

    You need the String#length property

    text.length
    

    instead of text.len.

    function alphabetPosition(text) {
        var chari,
            arr = [],
            alphabet = "abcdefghijklmnopqrstuvwxyz",
            i;
    
        for (var i = 0; i < text.length; i++){
            chari = text[i].toLowerCase();
            if (alphabet.indexOf(chari) !== -1){
                arr.push(alphabet.indexOf(chari));
            }
        }
        return arr;
    }
    console.log(alphabetPosition("Hello World!!1"));

    A solution with ES6

    function alphabetPosition(text) {
        return [...text].map(a => parseInt(a, 36) - 10).filter(a => a >= 0);
    }
    console.log(alphabetPosition("Hello World!!1"));

  2. 2017-01-02 13:01

    First : deleting space
    Second : mapping each char with its alphabet rank
    Third : test with the string Happy new year

    var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
    var alphabetPosition = text => 
      text.split('').map(x => alphabet.indexOf(x) + 1);
    console.log(alphabetPosition("happy new year"));

  3. 2017-01-02 13:01

    change len to length:

    (var i = 0; i < text.len; i++)
    // change to
    (var i = 0; i < text.length; i++)
    
  4. 2017-01-02 13:01

    You can make it even easier, by making use of the acii code. Because a = ascii code 97, b = 98 etc. And there is a javascript function String.charCodeAt( n ) which returns the ascii code at a specific function. You only have to alter the offset for capitals (if you want to support them).

    function alphabetPosition( text ) {
    	var positions = [];
    	for ( var i = 0; i < text.length; i++ ) {
    		var charCode = text.charCodeAt( i );
    		if ( charCode >= 97 && charCode <= 122 ) {
    			positions.push( charCode - 96 );
    		} else if ( charCode >= 65 && charCode <= 90 ) { // get rid of this if you don't care about capitals
    			positions.push( charCode - 64 );
    		}
    	}
    	return positions;
    }
    
    var positions = alphabetPosition( 'Hello World' );
    console.log(positions);

    Checkout this working fiddle

  5. 2017-01-02 13:01

    You can also use .charCodeAt function:

    function alphabetPosition(text) {
        start = "a".charCodeAt(0);
        end = "z".charCodeAt(0);
        res = [];
        for (var i = 0; i < text.length; i++) {
            index = text.charAt(i).toLowerCase().charCodeAt(0);
            if (index >= start && index <= end) {
                res.push(index - start +1); // +1 assuming a is 1 instead of 0
            } else {
                res.push(0); // Or do w/e you like with non-characters
            }
        }
        return res;
    }
    console.log(alphabetPosition("Hello World"));

  6. 2017-01-02 13:01

    The Kata works with this code. Try with this one:

    function alphabetPosition(text) {
      var result = "";
      for (var i = 0; i < text.length; i++) {
        var code = text.toUpperCase().charCodeAt(i)
        if (code > 64 && code < 91) result += (code - 64) + " ";
      }
    
      return result.slice(0, result.length - 1);
    }
    console.log(alphabetPosition("The sunset sets at twelve o' clock."));

  7. 2017-01-02 14:01

    You may do something like this;

    var alpha = [].reduce.call("abcdefghijklmnopqrstuvwxyz0123456789 .,!",(p,c,i) => (p[c] = i,p),{}),
          str = "Happy 2017 whatever..!",
        coded = [].map.call(str, c => alpha[c.toLowerCase()]);
    console.log(coded);

  8. 2017-01-02 14:01

    This example will return based on a 0 based array, and uses lambda expressions with filter. I recycle the original byte array created by splitting the text passed to the method.

    function alphabetPosition(text) {
      var bytes = text.split('');
      var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
      for (var i = 0, len = text.length; i < len; i++) {
    	bytes[i] = alphabet.indexOf(bytes[i].toLowerCase());
      }
      return bytes.filter(n => { if(n > -1) return n; } ).join(' ');
    }
    console.log(alphabetPosition("Hello World"));

    For a 1 based array result Kata Codewars Friendly

    function alphabetPosition(text) {
      var bytes = text.split('');
      var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
      for (var i = 0, len = text.length; i < len; i++) {
    	bytes[i] = alphabet.indexOf(bytes[i].toLowerCase()) + 1;
      }
      return bytes.filter(n => { if(n > 0) return n; } ).join(' ');
    }
    console.log(alphabetPosition("Hello World"));

  9. 2017-01-02 15:01

    Here is a much shorter version that does the same:

    function alphabetPosition(text){
      return text.split('').map(function(character){ return character.charCodeAt(0) - 'a'.charCodeAt(0) + 1; })
    }
    
    console.log(alphabetPosition("Hello World"));
    

Leave a reply to - Replace a letter with its alphabet position

◀ Go back