Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!