2

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?

2
  • 1
    arr[i]>longest should be arr[i].length>longest.length Commented Sep 19, 2018 at 18:09
  • Compare the length property in your if condition instead of comparing string. Commented Sep 19, 2018 at 18:10

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

4

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)

2 Comments

This does not explain what is wrong with the original code.
You can ignore the last parameter , "" of reduce for initialization
2

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

6 Comments

One critique of this method vs. the reduce example is that it takes longer to sort than to iterate only once over every item. Nevertheless, it is a clever solution.
@BenSteward You are right. As far I know the reduce method is O(n) while this is O(n log(n))
Yep. Still creative though. Can’t resist those one liners.
Wow, this is way over my knowledge right now! 😅 It was specified in the assignment to not use sort though, still, that was my first try actually. That try wasn't nearly as pretty as this one though.
@SoX It is just practice and the usage of es6 syntax. For example this is your same code in es6 and this as well
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.