

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Map numbers to characters in JavaScript
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' ]
- Related Questions & Answers
- Generate random characters and numbers in JavaScript?
- Map function and Lambda expression in Python to replace characters
- Map object in JavaScript.
- Object to Map conversion in JavaScript
- Converting numbers into corresponding alphabets and characters using JavaScript
- Map Sum Pairs in JavaScript
- Map anagrams to one another in JavaScript
- Convert object to a Map - JavaScript
- JavaScript: How to map array values without using "map" method?
- How to create an image map in JavaScript?
- Making your first map in javascript
- Object.keys().map() VS Array.map() in JavaScript
- Convert number to characters in JavaScript
- Escape characters in JavaScript
- JavaScript map value to keys (reverse object mapping)
Advertisements