Better Solution for: Basic Algorithm Scripting: Find the Longest Word in a String

<%= @topic_view.topic.title %>
<%= @topic_view.topic.average_rating %> <%= @topic_view.topic.posts.count { |p| !!p.custom_fields['rating'] } %>

Hi guys, I might have a little better solution for the “Basic Algorithm Scripting: Find the Longest Word in a String” challenge than found in its hint section.

The current solution is:

function findLongestWordLength(str) {
  var words = str.split(' ');
  var maxLength = 0;

  for (var i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
    }
  }

  return maxLength;
}

My solution is:

function findLongestWordLength(str) {
  var myArr= str.split(' ');
  str="";
  for (let i=0; i < myArr.length; i++) {
    if (myArr[i].length > str.length) {
      str=myArr[i];
    }
  }
  return str.length;
}

Since:

  1. The default function has return str.length; already in it
  2. My code uses one less variable
  3. Holds the actual longest string value if needed
    I believe my result to be more efficient than the already given solution.

Do you agree? If so how can I have this code added to the hint section of this example?

Thanks!

1 Like

How about this one

function findLongestWordLength(str) {
  s="";
  str.split(' ').filter( (el) => {
    if (el.length > s.length) {
      s = el;
    }
  })
  return s.length;
}

Update

function findLongestWordLength(str) {
  s="";
  str.split(' ').forEach( (el) => {
    if (el.length > s.length) {
      s = el;
    }
  })
  return s.length;
}

Looks good!
However the filter method is a bit more “advanced” than the ones discussed at the basic level, would you agree?

1 Like

yes. Agreed!
:slight_smile: :wink: .

1 Like

@Tchoukoualeu
that’s an anti pattern… filter return a new array - if you don’t use that functionality you should use forEach


@Albert_Codestein
I wouldn’t suggest that, you are overwriting the function parameter

anyway, you can find here how to contribute to the guide articles:
https://contribute.freecodecamp.org/home/

2 Likes

Thanks for your input. Ive just learned something new.