Given a string containing digits from 2-9 inclusive, return all possible letter combinations in JAVA SCRIPT | JavaScript, Node.js, React.js and Angular.js Forum
J
JYOTI SHARMA Posted on 08/02/2022

Given a string containing digits from 2-9 inclusive, return all possible letter combinations 
that the number could represent. Return the answer in any order.

// A mapping of digit to letters (just like on the telephone buttons) is given below. 
// Note that 1 does not map to any letters.

// [1]  [2]  [3]
//  -   abc  def
// [4]  [5]  [6]
// ghi  jkl  mno
// [7]  [8]  [9]
// pqrs tuv  wxyz
// [*]  [0]  [#]
//      + 

// Input: digits = "23"
// Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

// Input: digits = ""
// Output: []

// Input: digits = "2"
// Output: ["a","b","c"]


Y
Yogesh Chawla Replied on 12/02/2022

Run this:

var value = 10;
console.log((value + 9).toString(36).toUpperCase());
//Output: J(10th Letter)

//or
console.log(String.fromCharCode(1+64)); //A
console.log(String.fromCharCode(2+64)); //B

//or
function numberToLetter(number) {
    if (isNaN(number)) {return undefined}
    number = Math.abs(Math.floor(number))

    const dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let index = number % dictionary.length;
    let quotient = number / dictionary.length;
    let result;
    
    if (number <= dictionary.length) {return numToLetterFinal(number)}  //Number is single digit.

    if (quotient >= 1) {
        //Number is bigger than our dictionary so recursively performing this function until we are done
        if (index === 0) {quotient--;}   //Go till last letter in the dictionary string
        result = numberToLetter(quotient);
    }

    if (index === 0) {index = dictionary.length;}   //Don't give empty string
    
    return result + numToLetterFinal(index);

    function numToLetterFinal(number) {
        //Takes a letter between 0 and max letter length and returns the corresponding letter
        if (number > dictionary.length || number < 0) {return undefined;}
        if (number === 0) {
            return '';
        } else {
            return dictionary.slice(number - 1, number)
			//The slice() method returns selected elements in an array, as a new array.
			//Or, The slice() method does not change the original array.
        }
    }
}

//Test:

console.log(numberToLetter(4))     //D
console.log(numberToLetter(52))    //AZ