i followed the code under 3. Find the Longest Word With the reduce() Method source
why does the result show 2 instead of 5? my logic as follows:
let arr = ['howss', 'fuund', 'se']
let longestLength = arr.reduce((longest, currentWord) =>
longest.length > currentWord.length ?
longest.length : currentWord.length , "")
console.log(longestLength)
also, how do i shift line 97 to start from the same position as line 92 in the image below? the formatting currently shows that line 97 is a part of line 93. the code runs fine however
The accumulator in the reduce function should be an number representing the length of the longest word so far, initially set to zero:
const arr = ['howss', 'fuund', 'se'];
const longestLength = arr.reduce((longestLen, currentWord) =>
longestLen > currentWord.length ? longestLen : currentWord.length
, 0);
console.log(longestLength);
If you want to set to as a string representing the longest word, you will need to compute it first, and then get the length after the loop ends:
const arr = ['howss', 'fuund', 'se'];
const longestLength = arr.reduce((longestWord, currentWord) =>
longestWord.length > currentWord.length ? longestWord : currentWord
, "").length;
console.log(longestLength);
Your intial value is an empty string - it should be zero so that you can add length values to it (the accumulator - longest) on each iteration.
There's no need to assign the length of currentWord to longest.length since longest is a single value. Just increment longest, and return it for the next iteration.
let arr = ['howss', 'fuund', 'se', 'guardian'];
let longestLength = arr.reduce((longest, currentWord) => {
if (currentWord.length > longest) {
longest = currentWord.length;
}
return longest;
}, 0);
console.log(longestLength)
Honestly, though, I wouldn't even use reduce for this.
const arr = ['howss', 'fuund', 'se', 'guardian'];
let len = 0;
for (let el of arr) {
if (el.length > len) len = el.length;
}
console.log(len);
This is because you are returning an empty string with each iteration and compare it to the next item. What you could do is return actual longest string and at final iteration return it's length;
let arr = ['se', 'howss', 'fuund','test', "a"]
let longestLength = arr.reduce((longest, currentWord, i, a) => ((longest = longest.length > currentWord.length ?
longest : currentWord), i == a.length-1 ? longest.length : longest))
console.log(longestLength)