# Why is this not a valid solution again?: Basic Algorithm Scripting: Find the Longest Word in a String

Hey guys,

although I already have solved this algorithm. using this solution:

this solution passed:

``````let stringArr = str.split(' '); //transform str into an arr;
let longestStr = 1; //default value for longestStr;
for(let i=0; i<stringArr.length; i++){
console.log(stringArr[i].length);
if(longestStr < stringArr[i].length) {
longestStr = stringArr[i].length;
}
}
return longestStr;

``````

But my first solution was usng ES6 & .sort() which looked like this:

this didn’t pass

``````function findLongestWordLength(str) {
// //transform string into an array of strings
let stringArr = str.split(' ');
// //sort array in descending order and return the length first array in the order which is the longest string in the array
const longestWord = stringArr.sort((a,b) => a.length < b.length);
return longestWord[0].length;
}

findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

``````

my logic for this challenge is like this:

1. transform the string into arr hence the .split(" ");
2. sort the array into descending order so that the first string array is the longest.
3. return the length of the first array in the order.

I tested it in repl.it and it returns the expected value being asked in the challenge which is the length of the longest word in the sentence, so why is it not being accepted as a solution?

I hope someone can shed some light on this.

nice solution.

I pasted your solution and it passes all the tests on my machine.

wuuuut??? that’s weird. let me try that again on my end.

It’s not weird behaviour, it doesn’t work because

Should be `const longestWord = stringArr.sort((a,b) => b.length - a.length);`.

Your code is not returning a correct value for the sort callback that is guaranteed to work regardless of how the browser vendor has implemented `sort`. I assume you’re using [a newer version (post September) of] Chrome. It works in most other browsers even though the return value (`true`/`false`) is basically incorrect (it should be -1 (or any negative number), 0 or 1 (or any positive number))

I tested it still didn’t work on my end using the “<” operator. so it has something to do with browser compatibility. it worked with “-” operator. time to read MDN docs. thanks @DanCouper.

1 Like

Yeah, this seems to be very recent, I’ve noticed a load of people on the forum with failing test cases when using `sort`this update is thing that caused it I think.

ECMAScript doesn’t specify how `sort` should work under-the-hood, only that the callback function should return -1, 0 or 1. And so afaik it worked everywhere using `>` or `<` up until that update, which affects Chrome and Node, when they decided to be strict about needing to return the correct thing to make sure that sorting always worked as expected

2 Likes