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
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)
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);
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);