In a sentence, how to know which word has the least characters?

Asked

Viewed 717 times

3

In a sentence, how to know which word has the least characters? What I did was turn the string into an array, but I could only return the smallest when it comes to an array of numbers, using Array.min But there is some way or better way to get back the smallest text string?

var strt = 'hello world'
var result = strt.split('')
console.log(typeof(result))

Array.min = function(result) {
    return Math.min.apply(Math, result);
    console.log(Array.min(result))
};
console.log(Array.min(result))
  • Behold these answers for the longest word and it is possible to realize the reverse logic.

4 answers

3

Knowing that each word is separated by space, just divide your sentence into words with code frase.split(' ');, then just check which word with the smallest size through the property lenght.

function MenorPalavra(frase) {
    var palavras = frase.split(' ');
    let menor = palavras[0];
    for (let i = 0; i < palavras.length; i++) {
        menor = palavras[i].length < menor.length ? palavras[i] : menor;
    }
    return menor;
}
console.log(MenorPalavra("a menor palavra deste texto é a letra a"));

2

I found this answer in the SOEN:

function findShortestWord(str) {
  var words = str.split(' ');
  var shortest = words.reduce((shortestWord, currentWord) => {
    return currentWord.length < shortestWord.length ? currentWord : shortestWord;
  }, words[0]);
  return shortest;
}
console.log(findShortestWord("The quick brown fox jumped over the lazy dog"));

Break the function to find the biggest word in a sentence:

function findLongestWord(str) {
  var longest = str.split(' ').reduce((longestWord, currentWord) =>{
    return currentWord.length > longestWord.length ? currentWord : longestWord;
  }, "");
  return longest;
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));

2

A simple way using .filter():

var strt  = 'Em uma frase como saber qual palavra com menos caractetes';
var strt2 = 'tem algum metodo ou melhor forma de conseguir retornar a menor string de texto';

console.log(curta(strt));  // exemplo 1
console.log(curta(strt2)); // exemplo 2

function curta(i){
   var idx, pal;
   i.split(' ').filter(a=>{
      if(!idx || a.length < idx) idx = a.length, pal = a;
   });
   return pal;
}

The filter will run the converted string in array with split and the if will check which is the shortest one. The parameter a of filter represents the string of each array index.

  • Lacked the length. rs

  • Uncle, that’s not what I meant, see my answer you’ll understand what I meant.

  • Got it now. But in my opinion, comparing string meta-values doesn’t really come into play, I think.

1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.