# Map numbers to characters in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have the number 12145. We are required to write a function that maps the digits of the number to English alphabets according to the following norms. The alphabets are to be mapped according to the 1 based index, like 'a' for 1 and 'b' for 2 'c' for 3 and so on.

There can be several ways for mapping a number. Let's take the above number 121415 for example,

It can be mapped as −

12145->1,2,1,4,5->a,b,a,d,e

It also can be −

12145->12,1,4,5->l,a,d,e

It can also be −

12145->12,14,5->l,n,e

and so on, but 12145 can't be 1,2,1,45 because there’s is no mapping for 45 in the alphabets. So, our function should return an array of all the permutations of the alphabet mappings.

The code for this will be −

## Example

const num = 12145;
const mapToAlphabets = num => {
const numStr = '' + num;
let res = [];
const shoveElements = (left, right) => {
if (!left.length) {
res.push(right.map(el => {
return (+el + 9).toString(36);
}).join(''));
return;
};
if(+left[0] > 0){
shoveElements(left.slice(1), right.concat(left[0]));
};
if(left.length >= 2 && +(left.slice(0, 2)) <= 26){
shoveElements(left.slice(2), right.concat(left.slice(0, 2)));
};
};
shoveElements(numStr, []);
return res;
}
console.log(mapToAlphabets(num));

## Output

The output in the console −

[ 'abade', 'abne', 'aude', 'lade', 'lne' ]
Published on 12-Oct-2020 11:03:12