Calculating the weight of a string in JavaScript


Weight of a character (alphabet):

The weight of an English alphabet is nothing just its 1-based index.

For example, the weight of 'c' is 3, 'k' is 11 and so on.

We are required to write a JavaScript function that takes in a lowercase string and calculates and returns the weight of that string.

Example

The code for this will be −

 Live Demo

const str = 'this is a string';
const calculateWeight = (str = '') => {
   str = str.toLowerCase();
   const legend = 'abcdefghijklmnopqrstuvwxyz';
   let weight = 0;
   const { length: l } = str;
   for(let i = 0; i < l; i++){
      const el = str[i];
      const curr = legend.indexOf(el);
      weight += (curr + 1);
   };
   return weight;
};
console.log(calculateWeight(str));

Output

And the output in the console will be −

172

Updated on: 24-Feb-2021

629 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements