Biggest sum of words of a string in js
I came up to solve this problem in javascript:
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.
my code is the following:
function high(x){
x = x.split(" ");
var bestWord = 0;
var bestWordS = "";
for (var i = 0; i < x.length; i++){
var word = x[i].split("");
var letter;
var wordScore;
switch(word[i]){
case "a":
letter = 1;
break;
case "b":
letter = 2;
break;
case "c":
letter = 3;
break;
case "d":
letter = 4;
break;
case "e":
letter = 5;
break;
case "f":
letter = 6;
break;
case "g":
letter = 7;
break;
case "h":
letter = 8;
break;
case "i":
letter = 9;
break;
case "j":
letter = 10;
break;
case "k":
letter = 11;
break;
case "l":
letter = 12;
break;
case "m":
letter = 13;
break;
case "n":
letter = 14;
break;
case "o":
letter = 15;
break;
case "p":
letter = 16;
break;
case "q":
letter = 17;
break;
case "r":
letter = 18;
break;
case "s":
letter = 19;
break;
case "t":
letter = 20;
break;
case "u":
letter = 21;
break;
case "v":
letter = 22;
break;
case "w":
letter = 23;
break;
case "x":
letter = 24;
break;
case "y":
letter = 25;
break;
case "z":
letter = 26;
break;
}
wordScore += letter;
if ( wordScore > bestWord){
bestWord = wordScore;
bestWordS = x[i];
}
}
return bestWordS;
}
I don't know what is wrong the function always returns an empty string ( "" )
javascript string character
add a comment |
I came up to solve this problem in javascript:
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.
my code is the following:
function high(x){
x = x.split(" ");
var bestWord = 0;
var bestWordS = "";
for (var i = 0; i < x.length; i++){
var word = x[i].split("");
var letter;
var wordScore;
switch(word[i]){
case "a":
letter = 1;
break;
case "b":
letter = 2;
break;
case "c":
letter = 3;
break;
case "d":
letter = 4;
break;
case "e":
letter = 5;
break;
case "f":
letter = 6;
break;
case "g":
letter = 7;
break;
case "h":
letter = 8;
break;
case "i":
letter = 9;
break;
case "j":
letter = 10;
break;
case "k":
letter = 11;
break;
case "l":
letter = 12;
break;
case "m":
letter = 13;
break;
case "n":
letter = 14;
break;
case "o":
letter = 15;
break;
case "p":
letter = 16;
break;
case "q":
letter = 17;
break;
case "r":
letter = 18;
break;
case "s":
letter = 19;
break;
case "t":
letter = 20;
break;
case "u":
letter = 21;
break;
case "v":
letter = 22;
break;
case "w":
letter = 23;
break;
case "x":
letter = 24;
break;
case "y":
letter = 25;
break;
case "z":
letter = 26;
break;
}
wordScore += letter;
if ( wordScore > bestWord){
bestWord = wordScore;
bestWordS = x[i];
}
}
return bestWordS;
}
I don't know what is wrong the function always returns an empty string ( "" )
javascript string character
1
You need to iterate overword
with a different variable thani
, sincei
is the index of the word in the sentence.
– Heretic Monkey
Nov 24 '18 at 19:07
1
Missing a loop to loop over letters in a word also. Your current loop is for each word. Inside that loop over characters
– charlietfl
Nov 24 '18 at 19:17
add a comment |
I came up to solve this problem in javascript:
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.
my code is the following:
function high(x){
x = x.split(" ");
var bestWord = 0;
var bestWordS = "";
for (var i = 0; i < x.length; i++){
var word = x[i].split("");
var letter;
var wordScore;
switch(word[i]){
case "a":
letter = 1;
break;
case "b":
letter = 2;
break;
case "c":
letter = 3;
break;
case "d":
letter = 4;
break;
case "e":
letter = 5;
break;
case "f":
letter = 6;
break;
case "g":
letter = 7;
break;
case "h":
letter = 8;
break;
case "i":
letter = 9;
break;
case "j":
letter = 10;
break;
case "k":
letter = 11;
break;
case "l":
letter = 12;
break;
case "m":
letter = 13;
break;
case "n":
letter = 14;
break;
case "o":
letter = 15;
break;
case "p":
letter = 16;
break;
case "q":
letter = 17;
break;
case "r":
letter = 18;
break;
case "s":
letter = 19;
break;
case "t":
letter = 20;
break;
case "u":
letter = 21;
break;
case "v":
letter = 22;
break;
case "w":
letter = 23;
break;
case "x":
letter = 24;
break;
case "y":
letter = 25;
break;
case "z":
letter = 26;
break;
}
wordScore += letter;
if ( wordScore > bestWord){
bestWord = wordScore;
bestWordS = x[i];
}
}
return bestWordS;
}
I don't know what is wrong the function always returns an empty string ( "" )
javascript string character
I came up to solve this problem in javascript:
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.
my code is the following:
function high(x){
x = x.split(" ");
var bestWord = 0;
var bestWordS = "";
for (var i = 0; i < x.length; i++){
var word = x[i].split("");
var letter;
var wordScore;
switch(word[i]){
case "a":
letter = 1;
break;
case "b":
letter = 2;
break;
case "c":
letter = 3;
break;
case "d":
letter = 4;
break;
case "e":
letter = 5;
break;
case "f":
letter = 6;
break;
case "g":
letter = 7;
break;
case "h":
letter = 8;
break;
case "i":
letter = 9;
break;
case "j":
letter = 10;
break;
case "k":
letter = 11;
break;
case "l":
letter = 12;
break;
case "m":
letter = 13;
break;
case "n":
letter = 14;
break;
case "o":
letter = 15;
break;
case "p":
letter = 16;
break;
case "q":
letter = 17;
break;
case "r":
letter = 18;
break;
case "s":
letter = 19;
break;
case "t":
letter = 20;
break;
case "u":
letter = 21;
break;
case "v":
letter = 22;
break;
case "w":
letter = 23;
break;
case "x":
letter = 24;
break;
case "y":
letter = 25;
break;
case "z":
letter = 26;
break;
}
wordScore += letter;
if ( wordScore > bestWord){
bestWord = wordScore;
bestWordS = x[i];
}
}
return bestWordS;
}
I don't know what is wrong the function always returns an empty string ( "" )
javascript string character
javascript string character
asked Nov 24 '18 at 19:04
DanikasDanikas
32
32
1
You need to iterate overword
with a different variable thani
, sincei
is the index of the word in the sentence.
– Heretic Monkey
Nov 24 '18 at 19:07
1
Missing a loop to loop over letters in a word also. Your current loop is for each word. Inside that loop over characters
– charlietfl
Nov 24 '18 at 19:17
add a comment |
1
You need to iterate overword
with a different variable thani
, sincei
is the index of the word in the sentence.
– Heretic Monkey
Nov 24 '18 at 19:07
1
Missing a loop to loop over letters in a word also. Your current loop is for each word. Inside that loop over characters
– charlietfl
Nov 24 '18 at 19:17
1
1
You need to iterate over
word
with a different variable than i
, since i
is the index of the word in the sentence.– Heretic Monkey
Nov 24 '18 at 19:07
You need to iterate over
word
with a different variable than i
, since i
is the index of the word in the sentence.– Heretic Monkey
Nov 24 '18 at 19:07
1
1
Missing a loop to loop over letters in a word also. Your current loop is for each word. Inside that loop over characters
– charlietfl
Nov 24 '18 at 19:17
Missing a loop to loop over letters in a word also. Your current loop is for each word. Inside that loop over characters
– charlietfl
Nov 24 '18 at 19:17
add a comment |
2 Answers
2
active
oldest
votes
Assuming that the "score" of each word is as in your example, you could simply:
Edit: fixed an issue with the sort function, thanks to @KoshVery
const scoresByLetter = "abcdefghijklmnopqrstuvwxyz".split('');
const sentence = "azzzzim zoom";
const words = sentence.split(" ");
//Declearing a function to calculate score for a single word
const calculateWordWeight = (word)=>{
return Array.prototype.reduce.apply(word, [(score, letter) =>{
return score + scoresByLetter.indexOf(letter);
},0]);
};
//Calculating score for each word
const scores = words.map(calculateWordWeight);
//Finding the highest score value
let highestScore = Math.max(scores);
//Then finding the highest value index
let highestScoreIndex = scores.indexOf(highestScore);
//Finally, finding the word by the index
let wordWithHighestScore = words[highestScoreIndex];
alert(wordWithHighestScore);
1
@Danikas, Why did you accepted this answer? It's wrong.let selectedWord = sentence.split(" ").sort().pop();
works wrong here as it sorts words alphabetically, not by score so for string"azimuth zoom"
it returnszoom
. Then score for the wrong result is being calculated...
– Kosh Very
Nov 25 '18 at 19:26
@KoshVery You are tottaliy correct, I messed up the the function, fixed it and kept it low performance as possible.
– Adi Darachi
Nov 25 '18 at 21:13
thank you for the update. It makes my previous comment irrelevant, but your updated answer has issues too. Split inscoresByLetter
is not really needed; you're overusingapply
; you have unnecessaryreturns
and brackets which you could avoid; you're passingcalculateWordWeight
wrapped into an anonimous function tomap
instead of passingcalculateWordWeight
itself; you have two unnecessary loops; your code is not a function as per PO question. All these look poor to me. Sorry if offended.
– Kosh Very
Nov 25 '18 at 22:55
add a comment |
You might store all your letters in a string and use indexOf
to get a letter score.
Also you might use one reduce
to get a word score and another reduce
to find a word with the greatest score:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => x.split(/s+/).reduce((a, w) => (w = [w, [...w].reduce((a, l) => a += 1 + abc.indexOf(l), 0)]) && ~~a[1] > w[1] ? a : w, )[0]
console.log(high('lorem ipsum dolor'));
Update for those who have troubles reading oneliners,
a very readable version using two nested for
loops:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => {
let words = x.split(/s+/);
let best, maxscore = 0;
for (let word of words) {
let score = 0;
for (let letter of word) {
score += 1 + abc.indexOf(letter);
}
if (score > maxscore) {
best = word;
maxscore = score;
}
}
return best;
}
console.log(high('lorem ipsum dolor'));
1
Just sharing my opinion, one-liners like this are highly not recommended. the code is not readable, and if you pass it through webpack or so, it dose not matter.
– Adi Darachi
Nov 25 '18 at 11:16
@AdiDarachi, if you use it 10 times a day it becomes easily readable. Anyway, thank you for your opinion.
– Kosh Very
Nov 25 '18 at 15:54
@kushVery Make sens, But usually when write code, other developers suppose to read and work with it, you write readable code for them, not for yourself. anyway, in my eyes, when you answer a question in a public website, so developers can later use this answer, the code should be easy and readable, this is the only reason I commented, sorry if offended.
– Adi Darachi
Nov 25 '18 at 21:22
@AdiDarachi, no problem, there is nothing offensive in your comment. Actually, code like this is really easy and straightforward to me and my team. If a developer cannot readreduce
expression, I'd suggest spending some time on this topic at MDN and W3Schools.
– Kosh Very
Nov 25 '18 at 22:33
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53461472%2fbiggest-sum-of-words-of-a-string-in-js%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Assuming that the "score" of each word is as in your example, you could simply:
Edit: fixed an issue with the sort function, thanks to @KoshVery
const scoresByLetter = "abcdefghijklmnopqrstuvwxyz".split('');
const sentence = "azzzzim zoom";
const words = sentence.split(" ");
//Declearing a function to calculate score for a single word
const calculateWordWeight = (word)=>{
return Array.prototype.reduce.apply(word, [(score, letter) =>{
return score + scoresByLetter.indexOf(letter);
},0]);
};
//Calculating score for each word
const scores = words.map(calculateWordWeight);
//Finding the highest score value
let highestScore = Math.max(scores);
//Then finding the highest value index
let highestScoreIndex = scores.indexOf(highestScore);
//Finally, finding the word by the index
let wordWithHighestScore = words[highestScoreIndex];
alert(wordWithHighestScore);
1
@Danikas, Why did you accepted this answer? It's wrong.let selectedWord = sentence.split(" ").sort().pop();
works wrong here as it sorts words alphabetically, not by score so for string"azimuth zoom"
it returnszoom
. Then score for the wrong result is being calculated...
– Kosh Very
Nov 25 '18 at 19:26
@KoshVery You are tottaliy correct, I messed up the the function, fixed it and kept it low performance as possible.
– Adi Darachi
Nov 25 '18 at 21:13
thank you for the update. It makes my previous comment irrelevant, but your updated answer has issues too. Split inscoresByLetter
is not really needed; you're overusingapply
; you have unnecessaryreturns
and brackets which you could avoid; you're passingcalculateWordWeight
wrapped into an anonimous function tomap
instead of passingcalculateWordWeight
itself; you have two unnecessary loops; your code is not a function as per PO question. All these look poor to me. Sorry if offended.
– Kosh Very
Nov 25 '18 at 22:55
add a comment |
Assuming that the "score" of each word is as in your example, you could simply:
Edit: fixed an issue with the sort function, thanks to @KoshVery
const scoresByLetter = "abcdefghijklmnopqrstuvwxyz".split('');
const sentence = "azzzzim zoom";
const words = sentence.split(" ");
//Declearing a function to calculate score for a single word
const calculateWordWeight = (word)=>{
return Array.prototype.reduce.apply(word, [(score, letter) =>{
return score + scoresByLetter.indexOf(letter);
},0]);
};
//Calculating score for each word
const scores = words.map(calculateWordWeight);
//Finding the highest score value
let highestScore = Math.max(scores);
//Then finding the highest value index
let highestScoreIndex = scores.indexOf(highestScore);
//Finally, finding the word by the index
let wordWithHighestScore = words[highestScoreIndex];
alert(wordWithHighestScore);
1
@Danikas, Why did you accepted this answer? It's wrong.let selectedWord = sentence.split(" ").sort().pop();
works wrong here as it sorts words alphabetically, not by score so for string"azimuth zoom"
it returnszoom
. Then score for the wrong result is being calculated...
– Kosh Very
Nov 25 '18 at 19:26
@KoshVery You are tottaliy correct, I messed up the the function, fixed it and kept it low performance as possible.
– Adi Darachi
Nov 25 '18 at 21:13
thank you for the update. It makes my previous comment irrelevant, but your updated answer has issues too. Split inscoresByLetter
is not really needed; you're overusingapply
; you have unnecessaryreturns
and brackets which you could avoid; you're passingcalculateWordWeight
wrapped into an anonimous function tomap
instead of passingcalculateWordWeight
itself; you have two unnecessary loops; your code is not a function as per PO question. All these look poor to me. Sorry if offended.
– Kosh Very
Nov 25 '18 at 22:55
add a comment |
Assuming that the "score" of each word is as in your example, you could simply:
Edit: fixed an issue with the sort function, thanks to @KoshVery
const scoresByLetter = "abcdefghijklmnopqrstuvwxyz".split('');
const sentence = "azzzzim zoom";
const words = sentence.split(" ");
//Declearing a function to calculate score for a single word
const calculateWordWeight = (word)=>{
return Array.prototype.reduce.apply(word, [(score, letter) =>{
return score + scoresByLetter.indexOf(letter);
},0]);
};
//Calculating score for each word
const scores = words.map(calculateWordWeight);
//Finding the highest score value
let highestScore = Math.max(scores);
//Then finding the highest value index
let highestScoreIndex = scores.indexOf(highestScore);
//Finally, finding the word by the index
let wordWithHighestScore = words[highestScoreIndex];
alert(wordWithHighestScore);
Assuming that the "score" of each word is as in your example, you could simply:
Edit: fixed an issue with the sort function, thanks to @KoshVery
const scoresByLetter = "abcdefghijklmnopqrstuvwxyz".split('');
const sentence = "azzzzim zoom";
const words = sentence.split(" ");
//Declearing a function to calculate score for a single word
const calculateWordWeight = (word)=>{
return Array.prototype.reduce.apply(word, [(score, letter) =>{
return score + scoresByLetter.indexOf(letter);
},0]);
};
//Calculating score for each word
const scores = words.map(calculateWordWeight);
//Finding the highest score value
let highestScore = Math.max(scores);
//Then finding the highest value index
let highestScoreIndex = scores.indexOf(highestScore);
//Finally, finding the word by the index
let wordWithHighestScore = words[highestScoreIndex];
alert(wordWithHighestScore);
const scoresByLetter = "abcdefghijklmnopqrstuvwxyz".split('');
const sentence = "azzzzim zoom";
const words = sentence.split(" ");
//Declearing a function to calculate score for a single word
const calculateWordWeight = (word)=>{
return Array.prototype.reduce.apply(word, [(score, letter) =>{
return score + scoresByLetter.indexOf(letter);
},0]);
};
//Calculating score for each word
const scores = words.map(calculateWordWeight);
//Finding the highest score value
let highestScore = Math.max(scores);
//Then finding the highest value index
let highestScoreIndex = scores.indexOf(highestScore);
//Finally, finding the word by the index
let wordWithHighestScore = words[highestScoreIndex];
alert(wordWithHighestScore);
const scoresByLetter = "abcdefghijklmnopqrstuvwxyz".split('');
const sentence = "azzzzim zoom";
const words = sentence.split(" ");
//Declearing a function to calculate score for a single word
const calculateWordWeight = (word)=>{
return Array.prototype.reduce.apply(word, [(score, letter) =>{
return score + scoresByLetter.indexOf(letter);
},0]);
};
//Calculating score for each word
const scores = words.map(calculateWordWeight);
//Finding the highest score value
let highestScore = Math.max(scores);
//Then finding the highest value index
let highestScoreIndex = scores.indexOf(highestScore);
//Finally, finding the word by the index
let wordWithHighestScore = words[highestScoreIndex];
alert(wordWithHighestScore);
edited Nov 25 '18 at 23:50
answered Nov 24 '18 at 19:23
Adi DarachiAdi Darachi
810622
810622
1
@Danikas, Why did you accepted this answer? It's wrong.let selectedWord = sentence.split(" ").sort().pop();
works wrong here as it sorts words alphabetically, not by score so for string"azimuth zoom"
it returnszoom
. Then score for the wrong result is being calculated...
– Kosh Very
Nov 25 '18 at 19:26
@KoshVery You are tottaliy correct, I messed up the the function, fixed it and kept it low performance as possible.
– Adi Darachi
Nov 25 '18 at 21:13
thank you for the update. It makes my previous comment irrelevant, but your updated answer has issues too. Split inscoresByLetter
is not really needed; you're overusingapply
; you have unnecessaryreturns
and brackets which you could avoid; you're passingcalculateWordWeight
wrapped into an anonimous function tomap
instead of passingcalculateWordWeight
itself; you have two unnecessary loops; your code is not a function as per PO question. All these look poor to me. Sorry if offended.
– Kosh Very
Nov 25 '18 at 22:55
add a comment |
1
@Danikas, Why did you accepted this answer? It's wrong.let selectedWord = sentence.split(" ").sort().pop();
works wrong here as it sorts words alphabetically, not by score so for string"azimuth zoom"
it returnszoom
. Then score for the wrong result is being calculated...
– Kosh Very
Nov 25 '18 at 19:26
@KoshVery You are tottaliy correct, I messed up the the function, fixed it and kept it low performance as possible.
– Adi Darachi
Nov 25 '18 at 21:13
thank you for the update. It makes my previous comment irrelevant, but your updated answer has issues too. Split inscoresByLetter
is not really needed; you're overusingapply
; you have unnecessaryreturns
and brackets which you could avoid; you're passingcalculateWordWeight
wrapped into an anonimous function tomap
instead of passingcalculateWordWeight
itself; you have two unnecessary loops; your code is not a function as per PO question. All these look poor to me. Sorry if offended.
– Kosh Very
Nov 25 '18 at 22:55
1
1
@Danikas, Why did you accepted this answer? It's wrong.
let selectedWord = sentence.split(" ").sort().pop();
works wrong here as it sorts words alphabetically, not by score so for string "azimuth zoom"
it returns zoom
. Then score for the wrong result is being calculated...– Kosh Very
Nov 25 '18 at 19:26
@Danikas, Why did you accepted this answer? It's wrong.
let selectedWord = sentence.split(" ").sort().pop();
works wrong here as it sorts words alphabetically, not by score so for string "azimuth zoom"
it returns zoom
. Then score for the wrong result is being calculated...– Kosh Very
Nov 25 '18 at 19:26
@KoshVery You are tottaliy correct, I messed up the the function, fixed it and kept it low performance as possible.
– Adi Darachi
Nov 25 '18 at 21:13
@KoshVery You are tottaliy correct, I messed up the the function, fixed it and kept it low performance as possible.
– Adi Darachi
Nov 25 '18 at 21:13
thank you for the update. It makes my previous comment irrelevant, but your updated answer has issues too. Split in
scoresByLetter
is not really needed; you're overusing apply
; you have unnecessary returns
and brackets which you could avoid; you're passing calculateWordWeight
wrapped into an anonimous function to map
instead of passing calculateWordWeight
itself; you have two unnecessary loops; your code is not a function as per PO question. All these look poor to me. Sorry if offended.– Kosh Very
Nov 25 '18 at 22:55
thank you for the update. It makes my previous comment irrelevant, but your updated answer has issues too. Split in
scoresByLetter
is not really needed; you're overusing apply
; you have unnecessary returns
and brackets which you could avoid; you're passing calculateWordWeight
wrapped into an anonimous function to map
instead of passing calculateWordWeight
itself; you have two unnecessary loops; your code is not a function as per PO question. All these look poor to me. Sorry if offended.– Kosh Very
Nov 25 '18 at 22:55
add a comment |
You might store all your letters in a string and use indexOf
to get a letter score.
Also you might use one reduce
to get a word score and another reduce
to find a word with the greatest score:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => x.split(/s+/).reduce((a, w) => (w = [w, [...w].reduce((a, l) => a += 1 + abc.indexOf(l), 0)]) && ~~a[1] > w[1] ? a : w, )[0]
console.log(high('lorem ipsum dolor'));
Update for those who have troubles reading oneliners,
a very readable version using two nested for
loops:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => {
let words = x.split(/s+/);
let best, maxscore = 0;
for (let word of words) {
let score = 0;
for (let letter of word) {
score += 1 + abc.indexOf(letter);
}
if (score > maxscore) {
best = word;
maxscore = score;
}
}
return best;
}
console.log(high('lorem ipsum dolor'));
1
Just sharing my opinion, one-liners like this are highly not recommended. the code is not readable, and if you pass it through webpack or so, it dose not matter.
– Adi Darachi
Nov 25 '18 at 11:16
@AdiDarachi, if you use it 10 times a day it becomes easily readable. Anyway, thank you for your opinion.
– Kosh Very
Nov 25 '18 at 15:54
@kushVery Make sens, But usually when write code, other developers suppose to read and work with it, you write readable code for them, not for yourself. anyway, in my eyes, when you answer a question in a public website, so developers can later use this answer, the code should be easy and readable, this is the only reason I commented, sorry if offended.
– Adi Darachi
Nov 25 '18 at 21:22
@AdiDarachi, no problem, there is nothing offensive in your comment. Actually, code like this is really easy and straightforward to me and my team. If a developer cannot readreduce
expression, I'd suggest spending some time on this topic at MDN and W3Schools.
– Kosh Very
Nov 25 '18 at 22:33
add a comment |
You might store all your letters in a string and use indexOf
to get a letter score.
Also you might use one reduce
to get a word score and another reduce
to find a word with the greatest score:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => x.split(/s+/).reduce((a, w) => (w = [w, [...w].reduce((a, l) => a += 1 + abc.indexOf(l), 0)]) && ~~a[1] > w[1] ? a : w, )[0]
console.log(high('lorem ipsum dolor'));
Update for those who have troubles reading oneliners,
a very readable version using two nested for
loops:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => {
let words = x.split(/s+/);
let best, maxscore = 0;
for (let word of words) {
let score = 0;
for (let letter of word) {
score += 1 + abc.indexOf(letter);
}
if (score > maxscore) {
best = word;
maxscore = score;
}
}
return best;
}
console.log(high('lorem ipsum dolor'));
1
Just sharing my opinion, one-liners like this are highly not recommended. the code is not readable, and if you pass it through webpack or so, it dose not matter.
– Adi Darachi
Nov 25 '18 at 11:16
@AdiDarachi, if you use it 10 times a day it becomes easily readable. Anyway, thank you for your opinion.
– Kosh Very
Nov 25 '18 at 15:54
@kushVery Make sens, But usually when write code, other developers suppose to read and work with it, you write readable code for them, not for yourself. anyway, in my eyes, when you answer a question in a public website, so developers can later use this answer, the code should be easy and readable, this is the only reason I commented, sorry if offended.
– Adi Darachi
Nov 25 '18 at 21:22
@AdiDarachi, no problem, there is nothing offensive in your comment. Actually, code like this is really easy and straightforward to me and my team. If a developer cannot readreduce
expression, I'd suggest spending some time on this topic at MDN and W3Schools.
– Kosh Very
Nov 25 '18 at 22:33
add a comment |
You might store all your letters in a string and use indexOf
to get a letter score.
Also you might use one reduce
to get a word score and another reduce
to find a word with the greatest score:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => x.split(/s+/).reduce((a, w) => (w = [w, [...w].reduce((a, l) => a += 1 + abc.indexOf(l), 0)]) && ~~a[1] > w[1] ? a : w, )[0]
console.log(high('lorem ipsum dolor'));
Update for those who have troubles reading oneliners,
a very readable version using two nested for
loops:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => {
let words = x.split(/s+/);
let best, maxscore = 0;
for (let word of words) {
let score = 0;
for (let letter of word) {
score += 1 + abc.indexOf(letter);
}
if (score > maxscore) {
best = word;
maxscore = score;
}
}
return best;
}
console.log(high('lorem ipsum dolor'));
You might store all your letters in a string and use indexOf
to get a letter score.
Also you might use one reduce
to get a word score and another reduce
to find a word with the greatest score:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => x.split(/s+/).reduce((a, w) => (w = [w, [...w].reduce((a, l) => a += 1 + abc.indexOf(l), 0)]) && ~~a[1] > w[1] ? a : w, )[0]
console.log(high('lorem ipsum dolor'));
Update for those who have troubles reading oneliners,
a very readable version using two nested for
loops:
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => {
let words = x.split(/s+/);
let best, maxscore = 0;
for (let word of words) {
let score = 0;
for (let letter of word) {
score += 1 + abc.indexOf(letter);
}
if (score > maxscore) {
best = word;
maxscore = score;
}
}
return best;
}
console.log(high('lorem ipsum dolor'));
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => x.split(/s+/).reduce((a, w) => (w = [w, [...w].reduce((a, l) => a += 1 + abc.indexOf(l), 0)]) && ~~a[1] > w[1] ? a : w, )[0]
console.log(high('lorem ipsum dolor'));
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => x.split(/s+/).reduce((a, w) => (w = [w, [...w].reduce((a, l) => a += 1 + abc.indexOf(l), 0)]) && ~~a[1] > w[1] ? a : w, )[0]
console.log(high('lorem ipsum dolor'));
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => {
let words = x.split(/s+/);
let best, maxscore = 0;
for (let word of words) {
let score = 0;
for (let letter of word) {
score += 1 + abc.indexOf(letter);
}
if (score > maxscore) {
best = word;
maxscore = score;
}
}
return best;
}
console.log(high('lorem ipsum dolor'));
const abc = 'abcdefghijklmnopqrstuvwxyz';
const high = (x) => {
let words = x.split(/s+/);
let best, maxscore = 0;
for (let word of words) {
let score = 0;
for (let letter of word) {
score += 1 + abc.indexOf(letter);
}
if (score > maxscore) {
best = word;
maxscore = score;
}
}
return best;
}
console.log(high('lorem ipsum dolor'));
edited Nov 25 '18 at 23:13
answered Nov 24 '18 at 21:32
Kosh VeryKosh Very
10.9k1925
10.9k1925
1
Just sharing my opinion, one-liners like this are highly not recommended. the code is not readable, and if you pass it through webpack or so, it dose not matter.
– Adi Darachi
Nov 25 '18 at 11:16
@AdiDarachi, if you use it 10 times a day it becomes easily readable. Anyway, thank you for your opinion.
– Kosh Very
Nov 25 '18 at 15:54
@kushVery Make sens, But usually when write code, other developers suppose to read and work with it, you write readable code for them, not for yourself. anyway, in my eyes, when you answer a question in a public website, so developers can later use this answer, the code should be easy and readable, this is the only reason I commented, sorry if offended.
– Adi Darachi
Nov 25 '18 at 21:22
@AdiDarachi, no problem, there is nothing offensive in your comment. Actually, code like this is really easy and straightforward to me and my team. If a developer cannot readreduce
expression, I'd suggest spending some time on this topic at MDN and W3Schools.
– Kosh Very
Nov 25 '18 at 22:33
add a comment |
1
Just sharing my opinion, one-liners like this are highly not recommended. the code is not readable, and if you pass it through webpack or so, it dose not matter.
– Adi Darachi
Nov 25 '18 at 11:16
@AdiDarachi, if you use it 10 times a day it becomes easily readable. Anyway, thank you for your opinion.
– Kosh Very
Nov 25 '18 at 15:54
@kushVery Make sens, But usually when write code, other developers suppose to read and work with it, you write readable code for them, not for yourself. anyway, in my eyes, when you answer a question in a public website, so developers can later use this answer, the code should be easy and readable, this is the only reason I commented, sorry if offended.
– Adi Darachi
Nov 25 '18 at 21:22
@AdiDarachi, no problem, there is nothing offensive in your comment. Actually, code like this is really easy and straightforward to me and my team. If a developer cannot readreduce
expression, I'd suggest spending some time on this topic at MDN and W3Schools.
– Kosh Very
Nov 25 '18 at 22:33
1
1
Just sharing my opinion, one-liners like this are highly not recommended. the code is not readable, and if you pass it through webpack or so, it dose not matter.
– Adi Darachi
Nov 25 '18 at 11:16
Just sharing my opinion, one-liners like this are highly not recommended. the code is not readable, and if you pass it through webpack or so, it dose not matter.
– Adi Darachi
Nov 25 '18 at 11:16
@AdiDarachi, if you use it 10 times a day it becomes easily readable. Anyway, thank you for your opinion.
– Kosh Very
Nov 25 '18 at 15:54
@AdiDarachi, if you use it 10 times a day it becomes easily readable. Anyway, thank you for your opinion.
– Kosh Very
Nov 25 '18 at 15:54
@kushVery Make sens, But usually when write code, other developers suppose to read and work with it, you write readable code for them, not for yourself. anyway, in my eyes, when you answer a question in a public website, so developers can later use this answer, the code should be easy and readable, this is the only reason I commented, sorry if offended.
– Adi Darachi
Nov 25 '18 at 21:22
@kushVery Make sens, But usually when write code, other developers suppose to read and work with it, you write readable code for them, not for yourself. anyway, in my eyes, when you answer a question in a public website, so developers can later use this answer, the code should be easy and readable, this is the only reason I commented, sorry if offended.
– Adi Darachi
Nov 25 '18 at 21:22
@AdiDarachi, no problem, there is nothing offensive in your comment. Actually, code like this is really easy and straightforward to me and my team. If a developer cannot read
reduce
expression, I'd suggest spending some time on this topic at MDN and W3Schools.– Kosh Very
Nov 25 '18 at 22:33
@AdiDarachi, no problem, there is nothing offensive in your comment. Actually, code like this is really easy and straightforward to me and my team. If a developer cannot read
reduce
expression, I'd suggest spending some time on this topic at MDN and W3Schools.– Kosh Very
Nov 25 '18 at 22:33
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53461472%2fbiggest-sum-of-words-of-a-string-in-js%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
You need to iterate over
word
with a different variable thani
, sincei
is the index of the word in the sentence.– Heretic Monkey
Nov 24 '18 at 19:07
1
Missing a loop to loop over letters in a word also. Your current loop is for each word. Inside that loop over characters
– charlietfl
Nov 24 '18 at 19:17