In a sentence, how to know which word with fewer characters?

3

In one sentence, how do you know which word has fewer characters? What I did was to transform the string into an array, but I was only able to return the smallest when it comes to an array of numbers, using Array.min But is there any method or best way to get the smallest text string back?

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))
    
asked by anonymous 24.08.2018 / 22:38

4 answers

3

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

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"));
    
24.08.2018 / 22:51
3

A simple form 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 traverse the string converted to array with split and if will check which one is shorter. The parameter a of filter represents the string of each array index.

    
24.08.2018 / 23:59
2

I found this answer in 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"));

It breaks 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"));
    
24.08.2018 / 22:40
1

All answers return the first smallest word of the string based on the length of the word.

But if you need JavaScript to declare the lowest of the smallest words of the same length, for example, between a and b or between B and a or between uma and com ?

See the results below:

("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 to the corresponding character in the right operator.

Understand that JavaScript does not compare 7 with 8 , but rather its ASCII values which are respectively 055 and 056

  

In the case of a with b compares 097 (a) with 098 (b)

     

In the case of B with a compares 066 (B) with 097 (a)

     

In the case of áma with com compares 225 109 097 (ama) with 099 111 109 (com) . Thus, 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

25.08.2018 / 16:56