Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
Print smallest name with javascript

I am facing a problem with javascript problem-solving. I am now trying to print out the smallest name from a named array. But I cannot print out it. It shows the different names. Would you mind helping me, please?

see the codes.

var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend[0];
for (var i = 0; i < tinyFriend.length; i++) {
  var char = tinyFriend[i];
  if (char < tiny) {
    tiny = char;
  }
}
console.log(tiny);

please tell me where to make the correction

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Just use the Reduce Method

var tinyFriend = ['hasan' , 'md' , 'mdhasan' , 'zahdhasan'];
var tiny = tinyFriend.reduce(function(a, b) {
    return a.length <= b.length ? a : b;
  });
console.log(tiny)

about 4 years ago · Juan Pablo Isaza Relatório

0

use the inbuilt sort method

var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend.sort((a, b) => a.length - b.length)[0];
console.log(tiny);

fix for original code

var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend[0];
for (var i = 0; i < tinyFriend.length; i++) {
  var char = tinyFriend[i];
  if (char.length < tiny.length) { // use length
    tiny = char;
  }
}
console.log(tiny);
about 4 years ago · Juan Pablo Isaza Relatório

0

You can simply use for-of loop here to get the smallest string in an array

var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];

let smallest;
for (let word of tinyFriend) {
  if (smallest !== undefined) smallest = word.length < smallest.length ? word : smallest;
  else smallest = word;
}

console.log(smallest);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda