admin管理员组

文章数量:1353303

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?

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?

Share Improve this question edited Sep 19, 2018 at 18:14 G Cadogan 1821 silver badge9 bronze badges asked Sep 19, 2018 at 18:08 SoXSoX 431 silver badge6 bronze badges 2
  • 1 arr[i]>longest should be arr[i].length>longest.length – Luis felipe De jesus Munoz Commented Sep 19, 2018 at 18:09
  • Compare the length property in your if condition instead of paring string. – Mohammad Usman Commented Sep 19, 2018 at 18:10
Add a ment  | 

3 Answers 3

Reset to default 4

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

本文标签: javascriptFind longest string in arrayStack Overflow