Sum all letters in a word according to their position in the alphabet

For example, if str=bob, b = 2 , o = 15 , b=2 so bob would give a total of 19.

function calcAlphabet (str) {
  var total = 0;
  var strArr = str.split("")
  var alphabet = { a:1 , b:2 , c:3 , d:4 , e:5, f:6 , g:7, h:8, i:9 , j:10 , k:11 , l:12, m:13, n:14 , o:15, p:16 ,q:17 , r:18 , s:19, t:20, u:21, v:22 , w:23 , x:24, y:25 , z:26}

for (var i = strArr[0]; i<strArr.length ; i++){
  total = total + alphabet[i]
}
return total;

calcAlphabet("example")

It only returns 0 so I’m making a mistake somewhere. calcAlphabet(“example”) should return 76

needed to change

for (var i = strArr[0]; i<strArr.length ; i++){
  total = total + alphabet[i]
}

to

for (var i = 0 ; i<strArr.length ; i++) {

total = total + alphabet [strArr[i]];

console.log(total)

}

It now outputs correctly.

What alternative/better code could be written to perform the same task?

lol. Ya ninjaed me and also fixed your own problem. good on you.

here’s one that is just a slight tweak:

function calcAlphabet(str) {
  var total = 0;
  var alphabet = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, l: 12, m: 13, n: 14, o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, u: 21, v: 22, w: 23, x: 24, y: 25, z: 26 }

  for (letter of str) {
    total += alphabet[letter]
  }
  return total;
}
calcAlphabet("example")
1 Like

And another one that I like a bit better:

function calcAlphabet(str) {
  let total = 0;
  for (letter in str.toLowerCase()) {
    total += str.charCodeAt(letter) - 96
  }
  return total;
}
calcAlphabet("example")

And one more. Probably my favorite so far:

function calcAlphabet(str) {
  return str.toLowerCase()
    .split('')
    .reduce((acc, curr) => acc + curr.charCodeAt(0) - 96, 0)
}
calcAlphabet("example")

and because I can’t leave well enough alone:

const calcAlphabet = str => str.toLowerCase()
  .split('').reduce((acc, curr) => acc + curr.charCodeAt(0) - 96, 0);
calcAlphabet("example");
1 Like

These look complicated but great! Thank you. I am currently trying to complete the following problem:

‘’ Given a string of words, you need to find the highest scoring word.

Each letter of a word scores points according to it’s position in the alphabet: a = 1, b = 2, c = 3 etc.

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lowercase and all inputs will be valid.’’

Now that I have (sort of) grasped the for loop being used to lookup some table, I need to manage an input into

function high(x)

where x consists of two different strings. The function should return the string which scores the higher amount of points which is determined by adding up each letter’s value.

How would I ‘‘upgrade’’ the original code so that it works with multiple string inputs? Hope this makes sense

I wouldn’t “upgrade” the other function, I would use it as a helper function to make high() work.
(and I guess with your problem parameters, the toLowerCase() in my solutions are unnecessary.)

essentially, what I’m talking about is something like this:

function high(str) {
    // divide str into the first and second word
    // figure out if calcAlphabet(firstWord) is bigger or calcAlphabet(secondWord)
    // return the bigger scoring word, or if they tie, firstWord
}

function calcAlphabet(str) {
    // your stuff you already figured out
}

Of course if the string is longer than two words, which it looks like it might be by the requirements, you’re gonna need a loop similar to the one you used in calcAlphabet()

function high(x){

var y = x[0]; //first string
var z = x[1]; //second string

yArr = y.split('')
zArr = z.split('')

var alphabet = { a:1 , b:2 , c:3 , d:4 , e:5 , f:6 , g:7 , h:8 , i:9, j:10 , k:11 , l:12, m:13, n:14 , 
o: 15, p:16 , q:17 , r:18 , s:19 , t:20, u:21 , v:22 , x:23, w:24, y:25 , z:26 }

var totalY=0;

for (var i=0 ; i<yArr.length ; i++){
  totalY = totalY + alphabet[yArr[i]];
}

var totalZ=0;

for(var j = 0 ; j<zArr.length ; j++) {
   totalZ= totalZ + alphabet[zArr[j]]
}

if (totalY==totalZ) {
    return y;  // As challenge states return the first string if both score the same
}

if (totalY>totalZ) {
return y; 
}

if (totalY<totalZ) {
return z;
}


}

Does the above satisfy the solution?

This is an assignment, not a comparison: comparisons are == or ===

I would use this, much less code:

if (totalZ > totalY) {return z;} else {return y;}

My mistake. Now corrected using ==

If you have more than two words this doesn’t work though. How can you make it so they ti works for any number of words?

Yeah I tried my best in making a standardised version that looks through n words but it’s easier to make a 2 words version first to check. Unfortunately, this has not sparked the intuition for making it work if the input is, say

“An example of text”

It only seems to work for

‘‘ExampleOne’’
‘‘ExampleTwo’’

It would compare the points of both and return the one with a higher score.

I want the function to be able to calculate multiple words in a string like

“I am an example” (this would score 114)

Unfortunately I am stuck so any guidance in the right direction would be appreciated.

I would do as first thing: wrap all the code needed to calculate the value of a word in its own function so it is reusable.

After that I will give you one hint… do you remember how to find the highest value in an array using a for loop? Try to combine the two things.

There may be various ways to do that, but this is certainly one.

Short answer: No.

@ilenia already pointed out some problems, but the first one is right at the top:

function high(x) {

  var y = x[0]; //first string
  var z = x[1]; //second string

  yArr = y.split('')
  zArr = z.split('')

The x that is being passed in is a string multiple words long, right? let’s say “Ieahleen NiSofwareEngineer”

so where you assign y the value of x[0] and x the value of x[1], what you are assigning to those variables are actually the 0th and 1st characters of the string, "Ieahleen NiSofwareEngineer": I and e

Something like this would make it work:

function high(x) {

  const inputArr = x.split(' ');
  const y = inputArr[0];
  const yArr = y.split('');
  const z = inputArr[1];
  const zArr = z.split('');

BUT I would not recommend this. Have you heard of the concept of DRY?

I think there will be a double loops to compare the character of the string to the keys of the alphabet Object.

function calcAlphabet(str){
	let alph = { a:1 , b:2 , c:3 , d:4 , e:5, f:6 , g:7, h:8, i:9 , 
		j:10 , k:11 , l:12, m:13, n:14 , o:15, p:16 ,q:17 , r:18 , 
		s:19, t:20, u:21, v:22 , w:23 , x:24, y:25 , z:26};
	let total = 0;
	let strSplitted = str.split('');
	for (let key of strSplitted){
		for(let keyed in alph){
			if(key === keyed){
				total += alph[keyed];
			}
		}
	}

	return console.log(total);
}

That seems unnecessary complex… if in your string you have an a, then alph[“a”] is already equal to 1. You don’t need the second loop to compare if you use the letters of the string to get the value.

alph[strSplitted[key]] is already a number