Why doesn't my code work?

Tell us what’s happening:
I’m trying to find the longest word in an array, this is what I’ve written so far (please do not laugh) but it works for some texts but not all. Why?

Your code so far

function findLongestWordLength(str) {
let strSplit = []
strSplit = str.split(' ');
let length = strSplit.map(word => {
  return word.length;
let strLength = length.sort();
let lastEle = strLength[strLength.length-1];
return lastEle;

findLongestWordLength("The quick brown fox jumped over the lazy dog");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36.

Challenge: Find the Longest Word in a String

Link to the challenge:

1 Like

It worked for me if I put a compare function in the sort method.

function compareNumbers(a, b) {
  return a - b;

so instead of just array.sort(), you put the function inside the sort parentheses.

1 Like

Hello there,

Add this to your code to help you debug:

let strLength = length.sort();
// Add the console.log

Also, read up on the .sort method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Hope this helps

1 Like

I did all of this before posting but sadly it didn’t work. Thank you for responding. I’m super grateful.

1 Like

Ah! I see. Thank you so much for responding, let me go try it out.

1 Like

It worked!!! Thank you CactusWren2020.