Finding the 1-based index score of a lowercase alpha string in JavaScript


Problem

We are required to write a JavaScript function that takes in a lowercase alphabet string. The index of ‘a’ in alphabets is 1, of ‘b’ is 2 ‘c’ is 3 … of ‘z’ is 26.

Our function should sum all the index of the string characters and return the result.

Example

Following is the code −

 Live Demo

const str = 'lowercasestring';
const findScore = (str = '') => {
   const alpha = 'abcdefghijklmnopqrstuvwxyz';
   let score = 0;
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      const index = alpha.indexOf(el);
      score += (index + 1);
   };
   return score;
};
console.log(findScore(str));

Output

Following is the console output −

188

Updated on: 20-Apr-2021

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements