Find the Longest Word in a String - Code Refactor?

Hi, this question is in regards to the Basic Algorithm Challenge Return Largest Numbers in an Array. The challenge is to return the largest number from each provided sub-array.

I have the following code, which passed the tests. What I want to know is can I refactor this using arrow functions, or just refactoring it in general? I really like the idea of shortening my code. Thanks for any help.

function largestOfFour(arr) {
  let largestNumsArr = {
    let largestNum = subArr[0];
    subArr.forEach(function(num) {
      if(num > largestNum) {
        largestNum = num;
    return largestNum;
  return largestNumsArr;

You can replace your callback functions with arrow functions if you like

In terms of simplifying your code… why are you doing a map when you just need to return a single number?

The code you’ve posted is for the wrong question, so I’d start by refactoring it to the correct question :stuck_out_tongue:

1 Like

Whoops! Not sure what got into me, but I’ve fixed it.

I would refactor the inside of the map into another function

You’re essentially writing a whole function in there for finding the max of an array of numbers

I’d suggest first creating a new function called maxArray, and calling it in the map, and trying to implement maxArray with reduce

it’s a simple use case for reduce that’s worth practicing as it’s the most powerful of the higher order functions but not as immediately straightforward

After that, just use Math.max(...subArr) instead :stuck_out_tongue:

1 Like

Thanks. I’ll give it a shot.

Function to Find the Longest Word in a String

function find_longest_word(str)
  var array1 = str.match(/\w[a-z]{0,}/gi);
  var result = array1[0];

  for(var x = 1 ; x < array1.length ; x++)
    if(result.length < array1[x].length)
    result = array1[x];
  return result;
console.log(find_longest_word('Web Development Tutorial'));

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

If you want to compare your solution to others, use the Get a hint button on the challenge and there are alternative solutions you can compare yours to. Also, you can probably search older posts using the forum search feature or google the challenge name and find more there.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.