简体   繁体   中英

Find longest string in array

I'm supposed to find the longest string in an array, but can't find what's wrong with my code. Something isn't working when trying to debug in Visual Studio Code it just won't detach. Please help me with what's wrong!

Code:

let arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborg"];

function long_string(arr){
   let longest="";
   for (let i=0;i<arr.length;i++){
      if (arr[i]>longest){
         longest=arr[i];
      }
   } 
   return longest;
}

long_string(arr)

Can anyone spot the mistake?

You need to check the length of the item and the stored longest string.

if (arr[i].length > longest.length) {
//        ^^^^^^^          ^^^^^^^

Just another hint, you could use the first item as start value for longest and start iterating from index 1 .

 function long_string(arr) { let longest = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i].length > longest.length) { longest = arr[i]; } } return longest; } let arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborg"]; console.log(long_string(arr)); 

You can use reduce method for this and check length of current string in each iteration.

 let arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborg"]; let result = arr.reduce((r, e) => r.length < e.length ? e : r, ""); console.log(result) 

Another way to to it would be sorting and getting the first item

 let arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborg"]; console.log(arr.sort((a,b)=>b.length-a.length)[0]) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM