Find the longest word in a String, is my solution good? [SPOILER!]

Hey!
I come up with solution that works:

function findLongestWord(str) {
  var str1 = str.split(" ").sort(function(a, b){
    return b.length - a.length;});
  return str1[0].length;
}

But i didn’t find anything too similar with my in this topic. Can you tell my if my is good or bad? And if bad, then why?

1 Like

Hey, if it works, it works!

If you want to test the efficiency of your algorithm against the wiki answers, you can find a sample script here:

1 Like

Hello, I have moved your post to the right category as it is not a wiki entry.

Messy Solution, but it worked!!

function findLongestWord(str) {
return str.split(" " ).sort(function (a,b){
return (b.length-a.length);}).join(" “).split(” “,1).join(” ").length;
}

findLongestWord(“May the force be with you”);

const findLongestWord = str =>
  Math.max(...str.split(' ').map(w => w.length))
1 Like

function findLongestWord(str) {
str = str.split(’ ');
var a = [];
for (var i = 0; i < str.length; i++){
a[i] = str[i].length;
}
return a.sort(function(a,b){
return b-a;
}
)[0];
}
findLongestWord(“The quick brown fox jumped over the lazy dog”);

This is my solution:

const longestWord = (str) => Math.max(...str.split(' ').map((word) => word.length))

The dotdotdot part is ES6’s spread operator, to read more about it:

This is my solution:
function findLongestWord(str) {
var firstArray = str.split(" ").map(function(val){
return val.length;
});
var max = Math.max(…firstArray);

return max;
}

findLongestWord(“The quick brown fox jumped over the lazy dog”);

Here my solution:

function largestOfFour(arr) {
  return arr.map((a) => Math.max(...a));
}