All answers return the first smallest word of the string based on word length.
But if you need Javascript to decide to inform the smallest of the smallest words of the same length, such as between a
and b
or between B
and a
or between uma
and com
?
See the following results:
("b"<"a") ? console.log("b é menor que a"): console.log("b não é menor que a");
("B"<"a") ? console.log("B é menor que a"): console.log("B não é menor que a");
("áma"<"com") ? console.log("áma é menor que com"): console.log("áma não é menor que com");
General rule for string comparisons with Javascript.
For string comparisons, Javascript converts each character of a string to its ASCII value. Each character, starting with the left operator, is compared with the corresponding character in the right operator.
Understand that Javascript does not compare 7
with 8
and its ASCII values
which are respectively 055
and 056
In the case of a
with b
compare 097
(a) with 098
(b)
In the case of B
with a
compare 066
(B) with 097
(to)
In the case of áma
with com
compare 225 109 097
(amen) with 099 111 109
(with). So from left to right 099
is less than 225
For this type of comparison the code is:
function MenorMesmo(str) {
var strSplit = str.split(' '),
maisLonga, menor, menorOld;
maisLonga = strSplit.length;
for(var i = 0; i < strSplit.length; i++){
if(strSplit[i].length <= maisLonga){
maisLonga = strSplit[i].length;
menor = strSplit[i] ;
menor>menorOld?menor=menorOld:menor;
menorOld=strSplit[i];
}
}
return menor;
}
console.log(MenorMesmo("Se perguntar ao JavaScript qual é a menor palavra entre todas as de menores comprimento E u U a A Á ÁUÁ quem você acha que retornará"));
console.log(MenorMesmo('uma frase com duas palavras com mesmo comprimento quero saber qual palavra será considerada menor pelo JavaScript, isso mesmo porque HUMANOS responderão primeira que lerem'));
ASCII Table
NOTE: for numerical values, the results are equal to what you would expect from your school algebra classes
Behold these answers for the longest word and it is possible to realize the reverse logic.
– danieltakeshi