How to turn words into whole numbers JavaScript?


We have to write a function that takes in a string as one and only argument, and return its equivalent number.

For example −

one five seven eight  -------> 1578
Two eight eight eight -------> 2888

This one is pretty straightforward; we iterate over the array of words splitted by whitespace and keep adding the appropriate number to the result.

The code for doing this will be −

Example

const wordToNum = (str) => {
   const legend = ['zero', 'one', 'two', 'three', 'four', 'five', 'six','seven', 'eight', 'nine'];
   return str.toLowerCase().split(" ").reduce((acc, val) => {
      const index = legend.indexOf(val);
      return (acc*10 + index);
   }, 0);
};
console.log(wordToNum('one five six eight'));
console.log(wordToNum('zero zero two zero eight'));
console.log(wordToNum('eight six seven five'));

Output

The output in the console will be −

1568
208
8675

Updated on: 24-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements