Find what numbers were pressed to get the word (opposite of phone number digit problem) in JavaScript


The mapping of the numerals to alphabets in the old keypad type phones used to be like this −

const mapping = {
   1: [],
   2: ['a', 'b', 'c'],
   3: ['d', 'e', 'f'],
   4: ['g', 'h', 'i'],
   5: ['j', 'k', 'l'],
   6: ['m', 'n', 'o'],
   7: ['p', 'q', 'r', 's'],
   8: ['t', 'u', 'v'],
   9: ['w', 'x', 'y', 'z']
};

We are required to write a JavaScript function that takes in an alphabet string and return the number combination pressed to type that string.

For example −

If the alphabet string is −

const str = 'mad';

Then the output number should be −

const output = [6, 2, 3];

Example

The code for this will be −

const mapping = {
   1: [],
   2: ['a', 'b', 'c'],
   3: ['d', 'e', 'f'],
   4: ['g', 'h', 'i'],
   5: ['j', 'k', 'l'],
   6: ['m', 'n', 'o'],
   7: ['p', 'q', 'acc', 's'],
   8: ['t', 'u', 'v'],
   9: ['w', 'x', 'y', 'z']
};
const convertToNumeral = (str = '') => {
   const entries = Object.entries(mapping);
   const res = entries.reduce((acc, [v, letters]) => {
      letters.forEach(l => acc[l] = +v);
      return acc;
   }, {});
   const result = Array.from(str, (el) => {
      return res[el];
   });
   return result;
};
console.log(convertToNumeral('mad'))

Output

And the output in the console will be −

[ 6, 2, 3 ]

Updated on: 24-Nov-2020

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements