Is there a better way to do this?

function findLongestWordLength(str) {
  let newArray = str.split(" ");
  let longest=0;
  for(let i=0;i<newArray.length;i++)
             longest = newArray[i].length;
  return longest;

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

Here’s the solution I came up with, with comments. It’s purposely condensed, potentially to a fault if you don’t have auto formatting (I ran it thru which is pretty opinionated, but its better than my own hehe)

// use a short-hand arrow function
const findLongestWordLength = str =>
  // split the string to get an array of "words"
    .split(" ")
    // we use reduce to iterate over every word, and update the "accumulator"
    // argument (longest) if the word has a longer lenght than the current longest.
      (longest, word) =>
        // using a ternary, if word.length is greater than the current longest
        // then we return word.length, otherwise return longest
        word.length > longest ? word.length : longest,
      // we start with the length of 0 initially.

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

Related codepen:

Resource links for the “features” I used in my solution missing from the original post.

  1. arrow functions
  2. reduce
  3. ternary

The idea and approach is the same, but using all the new fancier JS operators available in newer version :slight_smile:


What my algorithm does it creates two storage variable units counter and result and then it searches the string for an empty value.

When it encounters an empty value in the string it compares counter (counter increases for every value that is not empty) with the previous result stored if counter is greater than the result value it replaces the result value and resets to zero.

The last piece which is i+1==str.length accounts for the possibility that the longest word is at the end of the string and since we can’t find an empty value at the end of the string I had to find a way to compare counter to result without relying on an empty value
Try this

function findLongestWordLength(str) {
     let result=0;
     let counter=0;
     for(let i=0;i<str.length;i++){
          if(str[i]!=" "){
          }else if(counter>result){
  return result;

Here’s what I came up with… one iteration, it searches in linear time and makes only 8 comparisons for this example. Here, I’m iterating through str split into an array, keeping track of the current longest word, and the next word to compare it to. I believe it’s O(n) time complexity and O(1) space complexity.

findLongestWordLength = str => {
	if(!str) return "undefined";
	str = str.split(" ");

	let current = 0;
	let next = 1;

	while(next < str.length){

		//if next is longer than current, move current to the next's position 
        // then move next up by one to continue comparisons.
		if(str[next].length > str[current].length){
			current = next;
			next = current + 1;
		} else {
	//when all comparisons are done, whatever index current is at is the longest
	return str[current].length;

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

This code may not be better but definitely is an alternative way of doing it

const re = /^(\w|-)+\s?/
const re2 = /^(\w|-)+/
const findLongestWordLength = (str, result = 0) => 
  str.length > 0
    ? result < str.match(re2)[0].length
      ? findLongestWordLength(str.replace(re, ''), str.match(re2)[0].length)
      : findLongestWordLength(str.replace(re, ''), result )
    : result

This algorithm doesn’t account for the possibility of the longest word being the last word in the string.

It works fine and returns the right value if the longest word is anywhere but at the end of the string. Test this and see. try putting the longest word at the back of the string.

1 Like

What about this? Wouldn’t this work?

function findLongestWordLength(str) {
   return Math.max(...str.split(" ").map(e => e.length))

Thank you good catch! I needed to change

while(next < str.length - 1)


while(next < str.length)

I’ll update my code for that now :smiley:

1 Like