function findLongestWordLength(str) {
let String = str;
let regex = /\w+/gi;
let result = String.match(regex);
for(let i = 0;i<result.length;i++){
//return result[i];
console.log(result[i]);
let len = result[i].length;
console.log(len);
if(len > 6){
return result[i];
}
}
return result;
}
console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));
almost there,got the string lengths but how to return the only longest one.
avoid using String as a variable. It is a reserved keyword. It would be like trying to assign a value to the keyword function
or the keyword let
.
For this exercise, maybe you will find useful the spread operator and Math method
function findLongestWordLength(str) {
let Str = str;
let regex = /\w+/gi;
let result = Str.match(regex);
//console.log(result);
for(let i = 0;i<result.length;i++){
//console.log(result[i].length);
let newArr = [];
newArr.push(result[i]);
let power = Math.max([...newArr]);
//console.log(power);
console.log(newArr);
}
return str.length;
}
console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));
Code so far,I defined the array newArr and pushed the values into it,but not able to access them and power variable is not printing the required values.
I suggest looking st your code with this:
http://www.pythontutor.com/javascript.html
Also Math.max
expect a comma separated list - which you get with the spread operator, but not if you create a new array (remove the square parentheses) - you are also not passing a number inside there, so at some point you may want to get the string length
Also, if you put newArr = []
inside the loop it will never fill up with things but reset to empty at each iteration
.sort()
would be slower than just checking one by one.
My suggestion is .split()
and .reduce()
split to break the sentences in several words.
and reduce starts with a large array reduces it to one
(which is what you want: you want a bunch of length of words and reduce it to one word length)
Your’re probably right. However I think performance is not really what’s @topcoder is looking for…