function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
for (let i = 0; i < arr.length; i++) {
let counter = 0;
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
The objective of the function is to cycle through an array and find the longest word. I've been looking through this and everything seems correct, though, obviously something is wrong but I am not seeing it.
7 Answers 7
It is because you set count to zero on every iteration, i.e. rewrite to
function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0; // Moved here!!!
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
Comments
I know this is a whole different approach but you can achieve same result using this more concise code, and without needing to apply any loop structure:
function LongestWord(sen) {
let arr = sen.split(' ');
return arr.sort(function(a, b){
// Sort Descending
return b.length - a.length;
})[0]; // Take first and longest element
}
Comments
You need to use counter out of for loop. Because as you're using in for loop every time it is getting re-initialized.
function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
console.log(LongestWord('heya 1 2'))
Comments
You are redeclaring counter with every iteration.
function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
Comments
You need to define counter outside of the loo, because you need it for keeping the length
function longestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
}
console.log(longestWord('orange banana potatoe hackfleischbällchen rice'))
Comments
function LongestWord(sen) {
let arr = sen.split(' ');
let longestWord;
let counter = 0; // you need to place counter outside for loop
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > counter) {
counter = arr[i].length;
longestWord = arr[i];
}
}
return longestWord;
};
console.log(LongestWord('something is wrong with this'));
Comments
How about something like this
# cat longest_word.js
function longestWord(str) {
return str.split(' ').reduce(function (acc, word) {
return acc.length > word.length ? acc : word;
});
}
console.log(longestWord('the quick brown fox jumps over the lazy dog'));
# node longest_word.js
jumps
#
forloop.