The function sumAscii should take an array of names and calculate each name’s score based on the total of each character’s lowercase ASCII value. It should return the name with the highest score. E.g. The name ‘John’ would get the score 431 because ‘j’ has the ASCII code 106, ‘o’ has the ASCII code 111, ‘h’ has the ASCII code 104 and ‘n’ has the ASCII code 110.
function sumAscii(arrayOfNames) {
function getAsciiScore() {
let sum = 0;
let arrayOfAsciiCodes = [];
for (const name of arrayOfNames) {
name.split("").forEach((letter) => {
sum += letter.toLowerCase().charCodeAt(0);
});
}
return sum;
}
let highestScore = "";
for (const name of arrayOfNames) {
for (const letter of name) {
return getAsciiScore(letter);
}
}
}
My function returns the total Ascii code score of all the names
2
Answers
Your code is almost ready. You just need to fix some logic errors:
Here’s a shorter method:
But this is more inefficient than your code since it calculates each word’s score multiple times. But this way is ok for small lists of small names.
This can be fixed with by storing the words with their score.
This is still less efficient, but the code is cleaner.
I just wanted to give it a shot and show another solution. I think you can use the map, reduce and Math.max function (the latter gives you the highest number in array). You can get the desired result as follow where I am returning an object with the index of the name with the highest sum, that name and the highest sum