SoX
SoX

Reputation: 43

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?

Upvotes: 2

Views: 5617

Answers (3)

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

Upvotes: 2

Nenad Vracar
Nenad Vracar

Reputation: 122047

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)

Upvotes: 4

Nina Scholz
Nina Scholz

Reputation: 386600

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

Upvotes: 4

Related Questions