Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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 −
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
Advertisements