I have seen various answers which give a solution to finding the longest string in an array. My problem is, I want to find the longest string in a nested array. The nesting level may be of N-levels or just two levels deep. My initial solution is as follows:
let myArray = [
'ABC',
'ABCD',
'ABCDE',
[
'ABC',
'ABCABABA',
[
'ABABABABABABABABAZZ'
],
'ABCABABASS',
],
'ABCDEFGH',
'ABABABABZZQ'
]
function longestString(arr) {
let longestStr = ''
arr.forEach(item => {
if(typeof item === 'string') {
if(item.length > longestStr.length) {
longestStr = item;
console.log('Longest Item', item);
}
} else {
longestString(item)
}
})
return longestStr;
}
console.log(longestString(myArray))
Observed Output -> ABABABABZZQ
Expected Output -> 'ABABABABABABABABAZZ'
What is the tweak needed to print only the longest string?
longestString. Instead, each iteration of the function should just return the longest string found, and when calling recursively, you should compare the returned value to the current stored longest string.