Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to programming and javascript.
I am struggling to understand how to make this code print out all the strings that are longer in the array.

I want to write a function that takes in an array of strings and then prints out the longest one

for example: longestWord(["the","fresh","green", "dog", "chased", "my", "chickens"])

should print: chickens

And If there are multiple longest strings then print them all in a different line.

for example: longestWord(["what", "about", "elephants", "and", "a", "crocodile"])

should print:
elephants
crocodile


What I have tried:

JavaScript
let array = ["Lions", "are", "incredibly", "elephant", "orange", "genuinelys"];

let sorted = array.sort(function (a, b){
     return b.length - a.length;
});

console.log(sorted[0]);


//This prints out only "incredibly"
Posted
Updated 10-Aug-21 10:22am

It prints only "incredibly" because that is what you - or the author of that code at least - told it to do:
Java
console.log(sorted[0]);

If you want it to pint more than one word, you need to tell it to print them, either by adding more lines:
Java
console.log(sorted[0]);
console.log(sorted[1]);
...
console.log(sorted[sorted.length - 1]);
Or by using a loop.
 
Share this answer
 
Just add two lines:
sortedAll = sorted
console.log(sortedAll);
 Result - (6) ["incredibly", "genuinelys", "elephant", "orange", "Lions", "are"]
sorted[5] will give you the 6th element of your array - the shortest.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900