0

This is my snippet. I feel this code satisfies the algorithm, but it does not pass. What could be the possible reason?

function findLongestWord(str, separator) {
    var splitString = str.split(separator);
    for (var i = 1; i <= splitString.length; i++) {
        for (j = 1; j < splitString[i].length; j++) {
            while (j === ' ') {
                return j;
            }
        }
    }
    var greater;
    if (j > greater) {
        greater = j;
    }
    return greater;
}

findLongestWord("The quick brown fox jumped over the lazy dog", ' ');
3
  • Possible duplicate of Javascript: find longest word in a string
    – Raviteja
    Jan 20, 2016 at 5:49
  • Can you show your output too
    – Amar Singh
    Jan 20, 2016 at 5:59
  • 1.The second loop is not necessary. 2.The variable greater is never be assigned. 3.@Mohammed Raja has a complete answer of your code.
    – Lin Yuan
    Jan 20, 2016 at 6:08

4 Answers 4

3

Here's your code with explanation and some changes to make it work

function findLongestWord(str, separator) {
    var splitString = str.split(separator);

    // Define it as empty string
    var greater = '';

    // Start looping from 0th index upto the length
    for (var i = 0; i < splitString.length; i++) {
        for (j = 0; j < splitString[i].length; j++) {
            // Don't know what this is
            // `j` is the index, i.e. number, it cannot be equal to ` `
            // I guess this is confused with the separator

            // This can be removed without any problem
            while (j === ' ') {
                return j;
            }
            // No use code
        }
        // Here `j` is the length of the word
        // Compare it with the length of greater word
        if (j > greater.length) {
            // Update the greater to current `i` string
            greater = splitString[i];
        }
    }

    // Return greater string.
    return greater;
}

var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' ');
document.body.innerHTML = 'Longest Word: ' + longestWord;


The same code with little optimizations can be re-written as

function findLongestWord(str, separator) {
    var splitString = str.split(separator);
    // Define it as empty string
    var greater = '';

    for (var i = 0, len = splitString.length; i < len; i++) {
        if (splitString[i].length > greater.length) {
            // Update the greater to current `i` string
            greater = splitString[i];
        }
    }

    return greater;
}

var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' ');
document.body.innerHTML = 'Longest Word: ' + longestWord;
console.log(longestWord);

My Solution using ES6

You can use Array#reduce and Arrow functions. For same code in ES5 check this answer by @gurvinder372

str.split(' ').reduce((x, y) => x.length > y.length ? x : y);

function findLongestWord(str, separator) {
    return str.split(' ').reduce((x, y) => x.length > y.length ? x : y);
}

var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' ');
document.body.innerHTML = 'Longest Word: ' + longestWord;
console.log(longestWord);

0
2

Try this fiddle

function findLongestWord(str, separator) {
    return str.split(separator).reduce(function (previousValue, currentValue) {
        return previousValue.length < currentValue.length ? currentValue : previousValue;
    });
}

var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' ');

console.log(longestWord);
document.body.innerHTML = longestWord;

3
  • 2
    The question is asking why the provided code doesn't work, not how to find the longest word. Jan 20, 2016 at 5:52
  • 2
    @Derek朕會功夫 I have no idea what OP's algorithm is. Two for loops and one while loop is not making any sense. But thats okay, I know OP's question is different and I will live with a downvote if that is what it takes to giving him a better solution :) Jan 20, 2016 at 5:57
  • 1
    This is real JavaScript. This is not an answer to the question, but it's still the best answer to this question.
    – buley
    Jan 20, 2016 at 6:12
1

Please try this:

function findLongestWord(str, separator) {
    var splitString = str.split(separator);  
    var greater = splitString[0];
    for (var i = 1; i < splitString.length; i++) {
        if(greater.length < splitString[i].length){
        greater = splitString[i]
      }
    }  
    return greater;
}

findLongestWord("The quick brown fox jumped over the lazy dog", ' ');
2
  • with some explanation should be better.
    – Lin Yuan
    Jan 20, 2016 at 6:11
  • After spliting into array, consider first element of the array i.e splitString[0] is a largest word. Browse through all words stored in array "splitString" and check length of each word against "greater". Jan 20, 2016 at 6:21
0

Javascript index starts from 0 to (length-1). After calling the split method on 'separator' argument, the words are stored in the splitString and indexed from 0 to (length-1). To find the longest word, before starting the loop we may safely assume that the first word is the longest. Then we can iterate over the words to check if any one is longer than this. If we find one, we can update our longest word. Your inner loop is redundant and the code can be write like this-

function findLongestWord(str, separator) {
var splitString = str.split(separator);
var greater = splitString[0];
for (var i = 1; i < splitString.length; i++) {
    if(greater.length < splitString[i].length)
    {
        greater = splitString[i];
    }
}
return greater; 
}
findLongestWord("The quick brown fox jumped over the lazy dog", ' ');

N.B.: If there are more than one word with the longest length, using this algorithm you will always find the first one searching from left to right. If you want the last one just change in if condition in the loop like this-

if(greater.length <= splitString[i].length)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.