We have a project that's requesting we prompt the end user for 3 different variables to go into an array. The purpose is to find the length of each string in the array and spit out the longest one.
let names = [];
const name1 = prompt("please enter name one")
const name2 = prompt("please enter name two")
const name3 = prompt("please enter name three")
names.push(name1,name2,name3);
function longest_string(str_ara) {
let max = str_ara[0].length;
str_ara.map(v => max = Math.max(max, v.length));
result = str_ara.filter(v => v.length == max);
return result;
}
console.log(longest_string([name1, name2,name3]) +' has the longest name');
Where I'm running into an issue is, we also are supposed to allow for multiple names to be listed if 2 or more are the same length. My initial thought was to write an if/else statement.
if (str_ara === name1) {
result = name1 + "has the longest name";
}
else if (str_ara === name2) {
result = name2 + "has the longest name";
}
else if (str_ara === name3) {
result = name3 + "has the longest name";
}
console.log(result);
but when I tried this, I got an error. Am I missing a call or put in the wrong variable? maybe need to use longest longest_string somehow?
I also tried
console.log(`The longest name is: ${longest_string(names)}`);
but that doesn't allow for the changes in text that we're requested to have.
If there's a better way to do this, I'm all ears!!
Aucun commentaire:
Enregistrer un commentaire