Find the longest string in a nested array using Recursion in Javascript?











up vote
0
down vote

favorite












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?










share|improve this question






















  • The problem is that you are printing inside 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.
    – Matt
    Nov 11 at 5:37










  • An equivalent solution to @Matt would be to pass the current longestStr as a parameter to the function so your can always compare the new strings to it. (Posted an answer here if it's not clear)
    – Nirit Levi
    Nov 11 at 6:49















up vote
0
down vote

favorite












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?










share|improve this question






















  • The problem is that you are printing inside 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.
    – Matt
    Nov 11 at 5:37










  • An equivalent solution to @Matt would be to pass the current longestStr as a parameter to the function so your can always compare the new strings to it. (Posted an answer here if it's not clear)
    – Nirit Levi
    Nov 11 at 6:49













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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?










share|improve this question













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?







javascript arrays recursion






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 5:33









SeaWarrior404

62311430




62311430












  • The problem is that you are printing inside 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.
    – Matt
    Nov 11 at 5:37










  • An equivalent solution to @Matt would be to pass the current longestStr as a parameter to the function so your can always compare the new strings to it. (Posted an answer here if it's not clear)
    – Nirit Levi
    Nov 11 at 6:49


















  • The problem is that you are printing inside 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.
    – Matt
    Nov 11 at 5:37










  • An equivalent solution to @Matt would be to pass the current longestStr as a parameter to the function so your can always compare the new strings to it. (Posted an answer here if it's not clear)
    – Nirit Levi
    Nov 11 at 6:49
















The problem is that you are printing inside 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.
– Matt
Nov 11 at 5:37




The problem is that you are printing inside 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.
– Matt
Nov 11 at 5:37












An equivalent solution to @Matt would be to pass the current longestStr as a parameter to the function so your can always compare the new strings to it. (Posted an answer here if it's not clear)
– Nirit Levi
Nov 11 at 6:49




An equivalent solution to @Matt would be to pass the current longestStr as a parameter to the function so your can always compare the new strings to it. (Posted an answer here if it's not clear)
– Nirit Levi
Nov 11 at 6:49












7 Answers
7






active

oldest

votes

















up vote
2
down vote



accepted










You need to use the return value of the recursive call - put the returned string through the same test that you put the item through, check if it's longer than longestStr, and if so, reassign longestStr:






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;
}
} else {
const nestedLongest = longestString(item);
if (nestedLongest.length > longestStr.length) {
longestStr = nestedLongest;
}
}
})
return longestStr;
}

console.log(longestString(myArray))





Or, to be somewhat more DRY:






const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

function longestString(arr) {
let longestStr = '';
const check = str => {
if (str.length > longestStr.length) longestStr = str;
};
arr.forEach(item => {
check(typeof item === 'string' ? item : longestString(item));
});
return longestStr;
}

console.log(longestString(myArray))





Another option would be to have an inner function that gets called, while assigning to a longestStr variable that's persistently in scope until the end of the longestString function - meaning that you don't have to worry about the results of the recursive calls:






const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

function longestString(input) {
let longestStr = '';
const check = str => {
if (str.length > longestStr.length) longestStr = str;
};
function recursiveFn(arr) {
arr.forEach((item) => {
if (typeof item === 'string') check(item)
else recursiveFn(item);
});
}
recursiveFn(input);
return longestStr;
}

console.log(longestString(myArray))








share|improve this answer






























    up vote
    1
    down vote













    Use Array.flat() to flatten the array, and then use Array.reduce() to find the longest item:






    const myArray = [
    'ABC',
    'ABCD',
    'ABCDE', [
    'ABC',
    'ABCABABA', [
    'ABABABABABABABABAZZ'
    ],
    'ABCABABASS',

    ],
    'ABCDEFGH',
    'ABABABABZZQ'
    ]

    const result = myArray
    .flat(Infinity)
    .reduce((r, s) => s.length > r.length ? s : r);

    console.log(result);








    share|improve this answer

















    • 1




      Problem with this method is that you are iterating the collection twice, it is quite inefficient. Not a real problem on a small data set but increases with the size of the input.
      – Adrian Brand
      Nov 11 at 5:45






    • 1




      This is a functional solution that splits the problem into two simple parts. Both parts are O(n), which translate to O(2n). In CS O(2n) is equivalent to O(n). This means that performance optimisation will be required only for huge arrays. In JS huge recursive solutions will fail most of the time (stack overflow).
      – Ori Drori
      Nov 11 at 5:55












    • Flat solution is what i also thought of!!!
      – Nitish Narang
      Nov 11 at 6:05










    • You do realise that flat is a recursive function? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
      – Adrian Brand
      Nov 11 at 8:03










    • And flat copies the array and consumes a huge amount of memory compared to a single reduce that only keeps a single string as an accumulator. The single reduce will only consume memory for the stack to the depth of the array nesting and will fail orders of magnitude later that flat.
      – Adrian Brand
      Nov 11 at 8:17


















    up vote
    1
    down vote













    You can do it with a single reduce






    const myArray = [
    'ABC',
    'ABCD',
    'ABCDE', [
    'ABC',
    'ABCABABA', [
    'ABABABABABABABABAZZ'
    ],
    'ABCABABASS',

    ],
    'ABCDEFGH',
    'ABABABABZZQ'
    ];

    const findLongestStr = array => array.reduce((result, item) => typeof item === 'string' ? item.length > result ? item : result : findLongestStr(item), '');

    console.log(findLongestStr(myArray));








    share|improve this answer




























      up vote
      1
      down vote













      You have to declare longestStr outside the function and also you have to use the return keyword



      return longestString(item)





      let myArray = [['ABC','ABCD','ABCDE',
      ['ABC','ABCABABA',
      ['ABABABABABABABABAZZ'],
      'ABCABABASS'],
      'ABCDEFGH',
      'ABABABABZZQ']]

      let longestStr = ''
      function longestString(arr) {
      arr.forEach(item => {
      if(typeof item === 'string') {
      if(item.length > longestStr.length) {
      longestStr = item;
      console.log('Longest Item', item);
      }
      } else {
      return longestString(item)
      }
      });
      return longestStr;
      }

      console.log(longestString(myArray));





      EDIT - You can pass longestStr as parameter to longestString function






      let myArray = [['ABC','ABCD','ABCDE',
      ['ABC','ABCABABA',
      ['ABABABABABABABABAZZ'],
      'ABCABABASS'],
      'ABCDEFGH',
      'ABABABABZZQ']]

      function longestString(arr,longestStr) {
      arr.forEach(item => {
      if(typeof item === 'string') {
      if(item.length > longestStr.length) {
      longestStr = item;
      console.log('Longest Item', item);
      }
      } else {
      var value = longestString(item,longestStr);
      if(value.length > longestStr.length){
      longestStr = value;
      }
      return longestStr;
      }
      });
      return longestStr;
      }

      console.log(longestString(myArray,''));








      share|improve this answer























      • You are maintaining the longestStr in the global context. We can passed as an argument to longestString itself.
        – front_end_dev
        Nov 11 at 5:48


















      up vote
      0
      down vote













      Recursively call the findLongestStr if the input is Array and maintain the current maximum value.



      let myArray = [
      'ABC',
      'ABCD',
      'ABCDE',
      [
      'ABC',
      'ABCABABA',
      [
      'ABABABABABABABABAZZ'
      ],
      'ABCABABASS',

      ],
      'ABCDEFGH',
      'ABABABABZZQ'
      ];

      function findLongestStr(input){
      return input.reduce(function(o,i){
      if(i.constructor === Array){
      var value = findLongestStr(i);
      console.log("value array => ",value);
      if(o.length < value.length){
      o = value;
      }
      }else{
      console.log("value i => ",i);
      if(o.length < i.length){
      o = i;
      }
      }
      return o;
      },"");
      }

      console.log("max length => ",findLongestStr(myArray));


      Working jsFiddle demo - https://jsfiddle.net/k4yo35hb/1/






      share|improve this answer




























        up vote
        0
        down vote













        The main problem with you code is that you redefine longestStr each time the recursive function is called. Leaving you no way of comparing the longest string from each recursive call.



        Using reduce() is a nice way to find the max of a regular un-nested array. You can add a little bit of recursion and still use reduce() for this which takes care of maintaining state between recursions because all the recursion unwinds within the reduce function:






        let myArray = ['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']


        function longestString(arr) {
        return arr.reduce((longest, item) => {
        if (Array.isArray(item)) {
        let rec = longestString(item)
        if (rec.length > longest.length) longest = rec
        } else if (item.length > longest.length) longest = item;

        return longest
        }, '')
        }

        console.log(longestString(myArray))








        share|improve this answer























        • Without providing the default intial value in reduce function it's getting undefined in longest at first place.
          – front_end_dev
          Nov 11 at 6:08






        • 1




          If you don't define the initial accumulator in a reduce function it uses the first element of the array, not undefined. In this case you need to define the accumulator as an empty string just incase the first item is an array.
          – Adrian Brand
          Nov 11 at 8:12


















        up vote
        0
        down vote













        with respect to @Adrian Brand clean answer, here is the solution:



        const findMaxStringInArray = (array, lastMax = '' ) => array.reduce((curMax,item)=>typeof item === 'string'?  item.length > curMax.length? item : curMax :  findMaxStringInArray(item, curMax) ,lastMax);





        share|improve this answer





















          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53246122%2ffind-the-longest-string-in-a-nested-array-using-recursion-in-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote



          accepted










          You need to use the return value of the recursive call - put the returned string through the same test that you put the item through, check if it's longer than longestStr, and if so, reassign longestStr:






          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;
          }
          } else {
          const nestedLongest = longestString(item);
          if (nestedLongest.length > longestStr.length) {
          longestStr = nestedLongest;
          }
          }
          })
          return longestStr;
          }

          console.log(longestString(myArray))





          Or, to be somewhat more DRY:






          const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

          function longestString(arr) {
          let longestStr = '';
          const check = str => {
          if (str.length > longestStr.length) longestStr = str;
          };
          arr.forEach(item => {
          check(typeof item === 'string' ? item : longestString(item));
          });
          return longestStr;
          }

          console.log(longestString(myArray))





          Another option would be to have an inner function that gets called, while assigning to a longestStr variable that's persistently in scope until the end of the longestString function - meaning that you don't have to worry about the results of the recursive calls:






          const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

          function longestString(input) {
          let longestStr = '';
          const check = str => {
          if (str.length > longestStr.length) longestStr = str;
          };
          function recursiveFn(arr) {
          arr.forEach((item) => {
          if (typeof item === 'string') check(item)
          else recursiveFn(item);
          });
          }
          recursiveFn(input);
          return longestStr;
          }

          console.log(longestString(myArray))








          share|improve this answer



























            up vote
            2
            down vote



            accepted










            You need to use the return value of the recursive call - put the returned string through the same test that you put the item through, check if it's longer than longestStr, and if so, reassign longestStr:






            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;
            }
            } else {
            const nestedLongest = longestString(item);
            if (nestedLongest.length > longestStr.length) {
            longestStr = nestedLongest;
            }
            }
            })
            return longestStr;
            }

            console.log(longestString(myArray))





            Or, to be somewhat more DRY:






            const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

            function longestString(arr) {
            let longestStr = '';
            const check = str => {
            if (str.length > longestStr.length) longestStr = str;
            };
            arr.forEach(item => {
            check(typeof item === 'string' ? item : longestString(item));
            });
            return longestStr;
            }

            console.log(longestString(myArray))





            Another option would be to have an inner function that gets called, while assigning to a longestStr variable that's persistently in scope until the end of the longestString function - meaning that you don't have to worry about the results of the recursive calls:






            const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

            function longestString(input) {
            let longestStr = '';
            const check = str => {
            if (str.length > longestStr.length) longestStr = str;
            };
            function recursiveFn(arr) {
            arr.forEach((item) => {
            if (typeof item === 'string') check(item)
            else recursiveFn(item);
            });
            }
            recursiveFn(input);
            return longestStr;
            }

            console.log(longestString(myArray))








            share|improve this answer

























              up vote
              2
              down vote



              accepted







              up vote
              2
              down vote



              accepted






              You need to use the return value of the recursive call - put the returned string through the same test that you put the item through, check if it's longer than longestStr, and if so, reassign longestStr:






              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;
              }
              } else {
              const nestedLongest = longestString(item);
              if (nestedLongest.length > longestStr.length) {
              longestStr = nestedLongest;
              }
              }
              })
              return longestStr;
              }

              console.log(longestString(myArray))





              Or, to be somewhat more DRY:






              const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

              function longestString(arr) {
              let longestStr = '';
              const check = str => {
              if (str.length > longestStr.length) longestStr = str;
              };
              arr.forEach(item => {
              check(typeof item === 'string' ? item : longestString(item));
              });
              return longestStr;
              }

              console.log(longestString(myArray))





              Another option would be to have an inner function that gets called, while assigning to a longestStr variable that's persistently in scope until the end of the longestString function - meaning that you don't have to worry about the results of the recursive calls:






              const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

              function longestString(input) {
              let longestStr = '';
              const check = str => {
              if (str.length > longestStr.length) longestStr = str;
              };
              function recursiveFn(arr) {
              arr.forEach((item) => {
              if (typeof item === 'string') check(item)
              else recursiveFn(item);
              });
              }
              recursiveFn(input);
              return longestStr;
              }

              console.log(longestString(myArray))








              share|improve this answer














              You need to use the return value of the recursive call - put the returned string through the same test that you put the item through, check if it's longer than longestStr, and if so, reassign longestStr:






              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;
              }
              } else {
              const nestedLongest = longestString(item);
              if (nestedLongest.length > longestStr.length) {
              longestStr = nestedLongest;
              }
              }
              })
              return longestStr;
              }

              console.log(longestString(myArray))





              Or, to be somewhat more DRY:






              const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

              function longestString(arr) {
              let longestStr = '';
              const check = str => {
              if (str.length > longestStr.length) longestStr = str;
              };
              arr.forEach(item => {
              check(typeof item === 'string' ? item : longestString(item));
              });
              return longestStr;
              }

              console.log(longestString(myArray))





              Another option would be to have an inner function that gets called, while assigning to a longestStr variable that's persistently in scope until the end of the longestString function - meaning that you don't have to worry about the results of the recursive calls:






              const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

              function longestString(input) {
              let longestStr = '';
              const check = str => {
              if (str.length > longestStr.length) longestStr = str;
              };
              function recursiveFn(arr) {
              arr.forEach((item) => {
              if (typeof item === 'string') check(item)
              else recursiveFn(item);
              });
              }
              recursiveFn(input);
              return longestStr;
              }

              console.log(longestString(myArray))








              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;
              }
              } else {
              const nestedLongest = longestString(item);
              if (nestedLongest.length > longestStr.length) {
              longestStr = nestedLongest;
              }
              }
              })
              return longestStr;
              }

              console.log(longestString(myArray))





              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;
              }
              } else {
              const nestedLongest = longestString(item);
              if (nestedLongest.length > longestStr.length) {
              longestStr = nestedLongest;
              }
              }
              })
              return longestStr;
              }

              console.log(longestString(myArray))





              const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

              function longestString(arr) {
              let longestStr = '';
              const check = str => {
              if (str.length > longestStr.length) longestStr = str;
              };
              arr.forEach(item => {
              check(typeof item === 'string' ? item : longestString(item));
              });
              return longestStr;
              }

              console.log(longestString(myArray))





              const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

              function longestString(arr) {
              let longestStr = '';
              const check = str => {
              if (str.length > longestStr.length) longestStr = str;
              };
              arr.forEach(item => {
              check(typeof item === 'string' ? item : longestString(item));
              });
              return longestStr;
              }

              console.log(longestString(myArray))





              const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

              function longestString(input) {
              let longestStr = '';
              const check = str => {
              if (str.length > longestStr.length) longestStr = str;
              };
              function recursiveFn(arr) {
              arr.forEach((item) => {
              if (typeof item === 'string') check(item)
              else recursiveFn(item);
              });
              }
              recursiveFn(input);
              return longestStr;
              }

              console.log(longestString(myArray))





              const myArray=['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']

              function longestString(input) {
              let longestStr = '';
              const check = str => {
              if (str.length > longestStr.length) longestStr = str;
              };
              function recursiveFn(arr) {
              arr.forEach((item) => {
              if (typeof item === 'string') check(item)
              else recursiveFn(item);
              });
              }
              recursiveFn(input);
              return longestStr;
              }

              console.log(longestString(myArray))






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 11 at 5:46

























              answered Nov 11 at 5:37









              CertainPerformance

              68.8k143453




              68.8k143453
























                  up vote
                  1
                  down vote













                  Use Array.flat() to flatten the array, and then use Array.reduce() to find the longest item:






                  const myArray = [
                  'ABC',
                  'ABCD',
                  'ABCDE', [
                  'ABC',
                  'ABCABABA', [
                  'ABABABABABABABABAZZ'
                  ],
                  'ABCABABASS',

                  ],
                  'ABCDEFGH',
                  'ABABABABZZQ'
                  ]

                  const result = myArray
                  .flat(Infinity)
                  .reduce((r, s) => s.length > r.length ? s : r);

                  console.log(result);








                  share|improve this answer

















                  • 1




                    Problem with this method is that you are iterating the collection twice, it is quite inefficient. Not a real problem on a small data set but increases with the size of the input.
                    – Adrian Brand
                    Nov 11 at 5:45






                  • 1




                    This is a functional solution that splits the problem into two simple parts. Both parts are O(n), which translate to O(2n). In CS O(2n) is equivalent to O(n). This means that performance optimisation will be required only for huge arrays. In JS huge recursive solutions will fail most of the time (stack overflow).
                    – Ori Drori
                    Nov 11 at 5:55












                  • Flat solution is what i also thought of!!!
                    – Nitish Narang
                    Nov 11 at 6:05










                  • You do realise that flat is a recursive function? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
                    – Adrian Brand
                    Nov 11 at 8:03










                  • And flat copies the array and consumes a huge amount of memory compared to a single reduce that only keeps a single string as an accumulator. The single reduce will only consume memory for the stack to the depth of the array nesting and will fail orders of magnitude later that flat.
                    – Adrian Brand
                    Nov 11 at 8:17















                  up vote
                  1
                  down vote













                  Use Array.flat() to flatten the array, and then use Array.reduce() to find the longest item:






                  const myArray = [
                  'ABC',
                  'ABCD',
                  'ABCDE', [
                  'ABC',
                  'ABCABABA', [
                  'ABABABABABABABABAZZ'
                  ],
                  'ABCABABASS',

                  ],
                  'ABCDEFGH',
                  'ABABABABZZQ'
                  ]

                  const result = myArray
                  .flat(Infinity)
                  .reduce((r, s) => s.length > r.length ? s : r);

                  console.log(result);








                  share|improve this answer

















                  • 1




                    Problem with this method is that you are iterating the collection twice, it is quite inefficient. Not a real problem on a small data set but increases with the size of the input.
                    – Adrian Brand
                    Nov 11 at 5:45






                  • 1




                    This is a functional solution that splits the problem into two simple parts. Both parts are O(n), which translate to O(2n). In CS O(2n) is equivalent to O(n). This means that performance optimisation will be required only for huge arrays. In JS huge recursive solutions will fail most of the time (stack overflow).
                    – Ori Drori
                    Nov 11 at 5:55












                  • Flat solution is what i also thought of!!!
                    – Nitish Narang
                    Nov 11 at 6:05










                  • You do realise that flat is a recursive function? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
                    – Adrian Brand
                    Nov 11 at 8:03










                  • And flat copies the array and consumes a huge amount of memory compared to a single reduce that only keeps a single string as an accumulator. The single reduce will only consume memory for the stack to the depth of the array nesting and will fail orders of magnitude later that flat.
                    – Adrian Brand
                    Nov 11 at 8:17













                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  Use Array.flat() to flatten the array, and then use Array.reduce() to find the longest item:






                  const myArray = [
                  'ABC',
                  'ABCD',
                  'ABCDE', [
                  'ABC',
                  'ABCABABA', [
                  'ABABABABABABABABAZZ'
                  ],
                  'ABCABABASS',

                  ],
                  'ABCDEFGH',
                  'ABABABABZZQ'
                  ]

                  const result = myArray
                  .flat(Infinity)
                  .reduce((r, s) => s.length > r.length ? s : r);

                  console.log(result);








                  share|improve this answer












                  Use Array.flat() to flatten the array, and then use Array.reduce() to find the longest item:






                  const myArray = [
                  'ABC',
                  'ABCD',
                  'ABCDE', [
                  'ABC',
                  'ABCABABA', [
                  'ABABABABABABABABAZZ'
                  ],
                  'ABCABABASS',

                  ],
                  'ABCDEFGH',
                  'ABABABABZZQ'
                  ]

                  const result = myArray
                  .flat(Infinity)
                  .reduce((r, s) => s.length > r.length ? s : r);

                  console.log(result);








                  const myArray = [
                  'ABC',
                  'ABCD',
                  'ABCDE', [
                  'ABC',
                  'ABCABABA', [
                  'ABABABABABABABABAZZ'
                  ],
                  'ABCABABASS',

                  ],
                  'ABCDEFGH',
                  'ABABABABZZQ'
                  ]

                  const result = myArray
                  .flat(Infinity)
                  .reduce((r, s) => s.length > r.length ? s : r);

                  console.log(result);





                  const myArray = [
                  'ABC',
                  'ABCD',
                  'ABCDE', [
                  'ABC',
                  'ABCABABA', [
                  'ABABABABABABABABAZZ'
                  ],
                  'ABCABABASS',

                  ],
                  'ABCDEFGH',
                  'ABABABABZZQ'
                  ]

                  const result = myArray
                  .flat(Infinity)
                  .reduce((r, s) => s.length > r.length ? s : r);

                  console.log(result);






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 11 at 5:38









                  Ori Drori

                  71.5k127489




                  71.5k127489








                  • 1




                    Problem with this method is that you are iterating the collection twice, it is quite inefficient. Not a real problem on a small data set but increases with the size of the input.
                    – Adrian Brand
                    Nov 11 at 5:45






                  • 1




                    This is a functional solution that splits the problem into two simple parts. Both parts are O(n), which translate to O(2n). In CS O(2n) is equivalent to O(n). This means that performance optimisation will be required only for huge arrays. In JS huge recursive solutions will fail most of the time (stack overflow).
                    – Ori Drori
                    Nov 11 at 5:55












                  • Flat solution is what i also thought of!!!
                    – Nitish Narang
                    Nov 11 at 6:05










                  • You do realise that flat is a recursive function? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
                    – Adrian Brand
                    Nov 11 at 8:03










                  • And flat copies the array and consumes a huge amount of memory compared to a single reduce that only keeps a single string as an accumulator. The single reduce will only consume memory for the stack to the depth of the array nesting and will fail orders of magnitude later that flat.
                    – Adrian Brand
                    Nov 11 at 8:17














                  • 1




                    Problem with this method is that you are iterating the collection twice, it is quite inefficient. Not a real problem on a small data set but increases with the size of the input.
                    – Adrian Brand
                    Nov 11 at 5:45






                  • 1




                    This is a functional solution that splits the problem into two simple parts. Both parts are O(n), which translate to O(2n). In CS O(2n) is equivalent to O(n). This means that performance optimisation will be required only for huge arrays. In JS huge recursive solutions will fail most of the time (stack overflow).
                    – Ori Drori
                    Nov 11 at 5:55












                  • Flat solution is what i also thought of!!!
                    – Nitish Narang
                    Nov 11 at 6:05










                  • You do realise that flat is a recursive function? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
                    – Adrian Brand
                    Nov 11 at 8:03










                  • And flat copies the array and consumes a huge amount of memory compared to a single reduce that only keeps a single string as an accumulator. The single reduce will only consume memory for the stack to the depth of the array nesting and will fail orders of magnitude later that flat.
                    – Adrian Brand
                    Nov 11 at 8:17








                  1




                  1




                  Problem with this method is that you are iterating the collection twice, it is quite inefficient. Not a real problem on a small data set but increases with the size of the input.
                  – Adrian Brand
                  Nov 11 at 5:45




                  Problem with this method is that you are iterating the collection twice, it is quite inefficient. Not a real problem on a small data set but increases with the size of the input.
                  – Adrian Brand
                  Nov 11 at 5:45




                  1




                  1




                  This is a functional solution that splits the problem into two simple parts. Both parts are O(n), which translate to O(2n). In CS O(2n) is equivalent to O(n). This means that performance optimisation will be required only for huge arrays. In JS huge recursive solutions will fail most of the time (stack overflow).
                  – Ori Drori
                  Nov 11 at 5:55






                  This is a functional solution that splits the problem into two simple parts. Both parts are O(n), which translate to O(2n). In CS O(2n) is equivalent to O(n). This means that performance optimisation will be required only for huge arrays. In JS huge recursive solutions will fail most of the time (stack overflow).
                  – Ori Drori
                  Nov 11 at 5:55














                  Flat solution is what i also thought of!!!
                  – Nitish Narang
                  Nov 11 at 6:05




                  Flat solution is what i also thought of!!!
                  – Nitish Narang
                  Nov 11 at 6:05












                  You do realise that flat is a recursive function? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
                  – Adrian Brand
                  Nov 11 at 8:03




                  You do realise that flat is a recursive function? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
                  – Adrian Brand
                  Nov 11 at 8:03












                  And flat copies the array and consumes a huge amount of memory compared to a single reduce that only keeps a single string as an accumulator. The single reduce will only consume memory for the stack to the depth of the array nesting and will fail orders of magnitude later that flat.
                  – Adrian Brand
                  Nov 11 at 8:17




                  And flat copies the array and consumes a huge amount of memory compared to a single reduce that only keeps a single string as an accumulator. The single reduce will only consume memory for the stack to the depth of the array nesting and will fail orders of magnitude later that flat.
                  – Adrian Brand
                  Nov 11 at 8:17










                  up vote
                  1
                  down vote













                  You can do it with a single reduce






                  const myArray = [
                  'ABC',
                  'ABCD',
                  'ABCDE', [
                  'ABC',
                  'ABCABABA', [
                  'ABABABABABABABABAZZ'
                  ],
                  'ABCABABASS',

                  ],
                  'ABCDEFGH',
                  'ABABABABZZQ'
                  ];

                  const findLongestStr = array => array.reduce((result, item) => typeof item === 'string' ? item.length > result ? item : result : findLongestStr(item), '');

                  console.log(findLongestStr(myArray));








                  share|improve this answer

























                    up vote
                    1
                    down vote













                    You can do it with a single reduce






                    const myArray = [
                    'ABC',
                    'ABCD',
                    'ABCDE', [
                    'ABC',
                    'ABCABABA', [
                    'ABABABABABABABABAZZ'
                    ],
                    'ABCABABASS',

                    ],
                    'ABCDEFGH',
                    'ABABABABZZQ'
                    ];

                    const findLongestStr = array => array.reduce((result, item) => typeof item === 'string' ? item.length > result ? item : result : findLongestStr(item), '');

                    console.log(findLongestStr(myArray));








                    share|improve this answer























                      up vote
                      1
                      down vote










                      up vote
                      1
                      down vote









                      You can do it with a single reduce






                      const myArray = [
                      'ABC',
                      'ABCD',
                      'ABCDE', [
                      'ABC',
                      'ABCABABA', [
                      'ABABABABABABABABAZZ'
                      ],
                      'ABCABABASS',

                      ],
                      'ABCDEFGH',
                      'ABABABABZZQ'
                      ];

                      const findLongestStr = array => array.reduce((result, item) => typeof item === 'string' ? item.length > result ? item : result : findLongestStr(item), '');

                      console.log(findLongestStr(myArray));








                      share|improve this answer












                      You can do it with a single reduce






                      const myArray = [
                      'ABC',
                      'ABCD',
                      'ABCDE', [
                      'ABC',
                      'ABCABABA', [
                      'ABABABABABABABABAZZ'
                      ],
                      'ABCABABASS',

                      ],
                      'ABCDEFGH',
                      'ABABABABZZQ'
                      ];

                      const findLongestStr = array => array.reduce((result, item) => typeof item === 'string' ? item.length > result ? item : result : findLongestStr(item), '');

                      console.log(findLongestStr(myArray));








                      const myArray = [
                      'ABC',
                      'ABCD',
                      'ABCDE', [
                      'ABC',
                      'ABCABABA', [
                      'ABABABABABABABABAZZ'
                      ],
                      'ABCABABASS',

                      ],
                      'ABCDEFGH',
                      'ABABABABZZQ'
                      ];

                      const findLongestStr = array => array.reduce((result, item) => typeof item === 'string' ? item.length > result ? item : result : findLongestStr(item), '');

                      console.log(findLongestStr(myArray));





                      const myArray = [
                      'ABC',
                      'ABCD',
                      'ABCDE', [
                      'ABC',
                      'ABCABABA', [
                      'ABABABABABABABABAZZ'
                      ],
                      'ABCABABASS',

                      ],
                      'ABCDEFGH',
                      'ABABABABZZQ'
                      ];

                      const findLongestStr = array => array.reduce((result, item) => typeof item === 'string' ? item.length > result ? item : result : findLongestStr(item), '');

                      console.log(findLongestStr(myArray));






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 11 at 5:52









                      Adrian Brand

                      2,50411018




                      2,50411018






















                          up vote
                          1
                          down vote













                          You have to declare longestStr outside the function and also you have to use the return keyword



                          return longestString(item)





                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          let longestStr = ''
                          function longestString(arr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          return longestString(item)
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray));





                          EDIT - You can pass longestStr as parameter to longestString function






                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          function longestString(arr,longestStr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          var value = longestString(item,longestStr);
                          if(value.length > longestStr.length){
                          longestStr = value;
                          }
                          return longestStr;
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray,''));








                          share|improve this answer























                          • You are maintaining the longestStr in the global context. We can passed as an argument to longestString itself.
                            – front_end_dev
                            Nov 11 at 5:48















                          up vote
                          1
                          down vote













                          You have to declare longestStr outside the function and also you have to use the return keyword



                          return longestString(item)





                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          let longestStr = ''
                          function longestString(arr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          return longestString(item)
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray));





                          EDIT - You can pass longestStr as parameter to longestString function






                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          function longestString(arr,longestStr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          var value = longestString(item,longestStr);
                          if(value.length > longestStr.length){
                          longestStr = value;
                          }
                          return longestStr;
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray,''));








                          share|improve this answer























                          • You are maintaining the longestStr in the global context. We can passed as an argument to longestString itself.
                            – front_end_dev
                            Nov 11 at 5:48













                          up vote
                          1
                          down vote










                          up vote
                          1
                          down vote









                          You have to declare longestStr outside the function and also you have to use the return keyword



                          return longestString(item)





                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          let longestStr = ''
                          function longestString(arr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          return longestString(item)
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray));





                          EDIT - You can pass longestStr as parameter to longestString function






                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          function longestString(arr,longestStr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          var value = longestString(item,longestStr);
                          if(value.length > longestStr.length){
                          longestStr = value;
                          }
                          return longestStr;
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray,''));








                          share|improve this answer














                          You have to declare longestStr outside the function and also you have to use the return keyword



                          return longestString(item)





                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          let longestStr = ''
                          function longestString(arr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          return longestString(item)
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray));





                          EDIT - You can pass longestStr as parameter to longestString function






                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          function longestString(arr,longestStr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          var value = longestString(item,longestStr);
                          if(value.length > longestStr.length){
                          longestStr = value;
                          }
                          return longestStr;
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray,''));








                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          let longestStr = ''
                          function longestString(arr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          return longestString(item)
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray));





                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          let longestStr = ''
                          function longestString(arr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          return longestString(item)
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray));





                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          function longestString(arr,longestStr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          var value = longestString(item,longestStr);
                          if(value.length > longestStr.length){
                          longestStr = value;
                          }
                          return longestStr;
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray,''));





                          let myArray = [['ABC','ABCD','ABCDE',
                          ['ABC','ABCABABA',
                          ['ABABABABABABABABAZZ'],
                          'ABCABABASS'],
                          'ABCDEFGH',
                          'ABABABABZZQ']]

                          function longestString(arr,longestStr) {
                          arr.forEach(item => {
                          if(typeof item === 'string') {
                          if(item.length > longestStr.length) {
                          longestStr = item;
                          console.log('Longest Item', item);
                          }
                          } else {
                          var value = longestString(item,longestStr);
                          if(value.length > longestStr.length){
                          longestStr = value;
                          }
                          return longestStr;
                          }
                          });
                          return longestStr;
                          }

                          console.log(longestString(myArray,''));






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 11 at 5:59

























                          answered Nov 11 at 5:40









                          Mamun

                          23.2k71428




                          23.2k71428












                          • You are maintaining the longestStr in the global context. We can passed as an argument to longestString itself.
                            – front_end_dev
                            Nov 11 at 5:48


















                          • You are maintaining the longestStr in the global context. We can passed as an argument to longestString itself.
                            – front_end_dev
                            Nov 11 at 5:48
















                          You are maintaining the longestStr in the global context. We can passed as an argument to longestString itself.
                          – front_end_dev
                          Nov 11 at 5:48




                          You are maintaining the longestStr in the global context. We can passed as an argument to longestString itself.
                          – front_end_dev
                          Nov 11 at 5:48










                          up vote
                          0
                          down vote













                          Recursively call the findLongestStr if the input is Array and maintain the current maximum value.



                          let myArray = [
                          'ABC',
                          'ABCD',
                          'ABCDE',
                          [
                          'ABC',
                          'ABCABABA',
                          [
                          'ABABABABABABABABAZZ'
                          ],
                          'ABCABABASS',

                          ],
                          'ABCDEFGH',
                          'ABABABABZZQ'
                          ];

                          function findLongestStr(input){
                          return input.reduce(function(o,i){
                          if(i.constructor === Array){
                          var value = findLongestStr(i);
                          console.log("value array => ",value);
                          if(o.length < value.length){
                          o = value;
                          }
                          }else{
                          console.log("value i => ",i);
                          if(o.length < i.length){
                          o = i;
                          }
                          }
                          return o;
                          },"");
                          }

                          console.log("max length => ",findLongestStr(myArray));


                          Working jsFiddle demo - https://jsfiddle.net/k4yo35hb/1/






                          share|improve this answer

























                            up vote
                            0
                            down vote













                            Recursively call the findLongestStr if the input is Array and maintain the current maximum value.



                            let myArray = [
                            'ABC',
                            'ABCD',
                            'ABCDE',
                            [
                            'ABC',
                            'ABCABABA',
                            [
                            'ABABABABABABABABAZZ'
                            ],
                            'ABCABABASS',

                            ],
                            'ABCDEFGH',
                            'ABABABABZZQ'
                            ];

                            function findLongestStr(input){
                            return input.reduce(function(o,i){
                            if(i.constructor === Array){
                            var value = findLongestStr(i);
                            console.log("value array => ",value);
                            if(o.length < value.length){
                            o = value;
                            }
                            }else{
                            console.log("value i => ",i);
                            if(o.length < i.length){
                            o = i;
                            }
                            }
                            return o;
                            },"");
                            }

                            console.log("max length => ",findLongestStr(myArray));


                            Working jsFiddle demo - https://jsfiddle.net/k4yo35hb/1/






                            share|improve this answer























                              up vote
                              0
                              down vote










                              up vote
                              0
                              down vote









                              Recursively call the findLongestStr if the input is Array and maintain the current maximum value.



                              let myArray = [
                              'ABC',
                              'ABCD',
                              'ABCDE',
                              [
                              'ABC',
                              'ABCABABA',
                              [
                              'ABABABABABABABABAZZ'
                              ],
                              'ABCABABASS',

                              ],
                              'ABCDEFGH',
                              'ABABABABZZQ'
                              ];

                              function findLongestStr(input){
                              return input.reduce(function(o,i){
                              if(i.constructor === Array){
                              var value = findLongestStr(i);
                              console.log("value array => ",value);
                              if(o.length < value.length){
                              o = value;
                              }
                              }else{
                              console.log("value i => ",i);
                              if(o.length < i.length){
                              o = i;
                              }
                              }
                              return o;
                              },"");
                              }

                              console.log("max length => ",findLongestStr(myArray));


                              Working jsFiddle demo - https://jsfiddle.net/k4yo35hb/1/






                              share|improve this answer












                              Recursively call the findLongestStr if the input is Array and maintain the current maximum value.



                              let myArray = [
                              'ABC',
                              'ABCD',
                              'ABCDE',
                              [
                              'ABC',
                              'ABCABABA',
                              [
                              'ABABABABABABABABAZZ'
                              ],
                              'ABCABABASS',

                              ],
                              'ABCDEFGH',
                              'ABABABABZZQ'
                              ];

                              function findLongestStr(input){
                              return input.reduce(function(o,i){
                              if(i.constructor === Array){
                              var value = findLongestStr(i);
                              console.log("value array => ",value);
                              if(o.length < value.length){
                              o = value;
                              }
                              }else{
                              console.log("value i => ",i);
                              if(o.length < i.length){
                              o = i;
                              }
                              }
                              return o;
                              },"");
                              }

                              console.log("max length => ",findLongestStr(myArray));


                              Working jsFiddle demo - https://jsfiddle.net/k4yo35hb/1/







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 11 at 5:45









                              front_end_dev

                              1,3151511




                              1,3151511






















                                  up vote
                                  0
                                  down vote













                                  The main problem with you code is that you redefine longestStr each time the recursive function is called. Leaving you no way of comparing the longest string from each recursive call.



                                  Using reduce() is a nice way to find the max of a regular un-nested array. You can add a little bit of recursion and still use reduce() for this which takes care of maintaining state between recursions because all the recursion unwinds within the reduce function:






                                  let myArray = ['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']


                                  function longestString(arr) {
                                  return arr.reduce((longest, item) => {
                                  if (Array.isArray(item)) {
                                  let rec = longestString(item)
                                  if (rec.length > longest.length) longest = rec
                                  } else if (item.length > longest.length) longest = item;

                                  return longest
                                  }, '')
                                  }

                                  console.log(longestString(myArray))








                                  share|improve this answer























                                  • Without providing the default intial value in reduce function it's getting undefined in longest at first place.
                                    – front_end_dev
                                    Nov 11 at 6:08






                                  • 1




                                    If you don't define the initial accumulator in a reduce function it uses the first element of the array, not undefined. In this case you need to define the accumulator as an empty string just incase the first item is an array.
                                    – Adrian Brand
                                    Nov 11 at 8:12















                                  up vote
                                  0
                                  down vote













                                  The main problem with you code is that you redefine longestStr each time the recursive function is called. Leaving you no way of comparing the longest string from each recursive call.



                                  Using reduce() is a nice way to find the max of a regular un-nested array. You can add a little bit of recursion and still use reduce() for this which takes care of maintaining state between recursions because all the recursion unwinds within the reduce function:






                                  let myArray = ['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']


                                  function longestString(arr) {
                                  return arr.reduce((longest, item) => {
                                  if (Array.isArray(item)) {
                                  let rec = longestString(item)
                                  if (rec.length > longest.length) longest = rec
                                  } else if (item.length > longest.length) longest = item;

                                  return longest
                                  }, '')
                                  }

                                  console.log(longestString(myArray))








                                  share|improve this answer























                                  • Without providing the default intial value in reduce function it's getting undefined in longest at first place.
                                    – front_end_dev
                                    Nov 11 at 6:08






                                  • 1




                                    If you don't define the initial accumulator in a reduce function it uses the first element of the array, not undefined. In this case you need to define the accumulator as an empty string just incase the first item is an array.
                                    – Adrian Brand
                                    Nov 11 at 8:12













                                  up vote
                                  0
                                  down vote










                                  up vote
                                  0
                                  down vote









                                  The main problem with you code is that you redefine longestStr each time the recursive function is called. Leaving you no way of comparing the longest string from each recursive call.



                                  Using reduce() is a nice way to find the max of a regular un-nested array. You can add a little bit of recursion and still use reduce() for this which takes care of maintaining state between recursions because all the recursion unwinds within the reduce function:






                                  let myArray = ['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']


                                  function longestString(arr) {
                                  return arr.reduce((longest, item) => {
                                  if (Array.isArray(item)) {
                                  let rec = longestString(item)
                                  if (rec.length > longest.length) longest = rec
                                  } else if (item.length > longest.length) longest = item;

                                  return longest
                                  }, '')
                                  }

                                  console.log(longestString(myArray))








                                  share|improve this answer














                                  The main problem with you code is that you redefine longestStr each time the recursive function is called. Leaving you no way of comparing the longest string from each recursive call.



                                  Using reduce() is a nice way to find the max of a regular un-nested array. You can add a little bit of recursion and still use reduce() for this which takes care of maintaining state between recursions because all the recursion unwinds within the reduce function:






                                  let myArray = ['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']


                                  function longestString(arr) {
                                  return arr.reduce((longest, item) => {
                                  if (Array.isArray(item)) {
                                  let rec = longestString(item)
                                  if (rec.length > longest.length) longest = rec
                                  } else if (item.length > longest.length) longest = item;

                                  return longest
                                  }, '')
                                  }

                                  console.log(longestString(myArray))








                                  let myArray = ['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']


                                  function longestString(arr) {
                                  return arr.reduce((longest, item) => {
                                  if (Array.isArray(item)) {
                                  let rec = longestString(item)
                                  if (rec.length > longest.length) longest = rec
                                  } else if (item.length > longest.length) longest = item;

                                  return longest
                                  }, '')
                                  }

                                  console.log(longestString(myArray))





                                  let myArray = ['ABC','ABCD','ABCDE',['ABC','ABCABABA',['ABABABABABABABABAZZ'],'ABCABABASS',],'ABCDEFGH','ABABABABZZQ']


                                  function longestString(arr) {
                                  return arr.reduce((longest, item) => {
                                  if (Array.isArray(item)) {
                                  let rec = longestString(item)
                                  if (rec.length > longest.length) longest = rec
                                  } else if (item.length > longest.length) longest = item;

                                  return longest
                                  }, '')
                                  }

                                  console.log(longestString(myArray))






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 11 at 6:11

























                                  answered Nov 11 at 5:56









                                  Mark Meyer

                                  31k32550




                                  31k32550












                                  • Without providing the default intial value in reduce function it's getting undefined in longest at first place.
                                    – front_end_dev
                                    Nov 11 at 6:08






                                  • 1




                                    If you don't define the initial accumulator in a reduce function it uses the first element of the array, not undefined. In this case you need to define the accumulator as an empty string just incase the first item is an array.
                                    – Adrian Brand
                                    Nov 11 at 8:12


















                                  • Without providing the default intial value in reduce function it's getting undefined in longest at first place.
                                    – front_end_dev
                                    Nov 11 at 6:08






                                  • 1




                                    If you don't define the initial accumulator in a reduce function it uses the first element of the array, not undefined. In this case you need to define the accumulator as an empty string just incase the first item is an array.
                                    – Adrian Brand
                                    Nov 11 at 8:12
















                                  Without providing the default intial value in reduce function it's getting undefined in longest at first place.
                                  – front_end_dev
                                  Nov 11 at 6:08




                                  Without providing the default intial value in reduce function it's getting undefined in longest at first place.
                                  – front_end_dev
                                  Nov 11 at 6:08




                                  1




                                  1




                                  If you don't define the initial accumulator in a reduce function it uses the first element of the array, not undefined. In this case you need to define the accumulator as an empty string just incase the first item is an array.
                                  – Adrian Brand
                                  Nov 11 at 8:12




                                  If you don't define the initial accumulator in a reduce function it uses the first element of the array, not undefined. In this case you need to define the accumulator as an empty string just incase the first item is an array.
                                  – Adrian Brand
                                  Nov 11 at 8:12










                                  up vote
                                  0
                                  down vote













                                  with respect to @Adrian Brand clean answer, here is the solution:



                                  const findMaxStringInArray = (array, lastMax = '' ) => array.reduce((curMax,item)=>typeof item === 'string'?  item.length > curMax.length? item : curMax :  findMaxStringInArray(item, curMax) ,lastMax);





                                  share|improve this answer

























                                    up vote
                                    0
                                    down vote













                                    with respect to @Adrian Brand clean answer, here is the solution:



                                    const findMaxStringInArray = (array, lastMax = '' ) => array.reduce((curMax,item)=>typeof item === 'string'?  item.length > curMax.length? item : curMax :  findMaxStringInArray(item, curMax) ,lastMax);





                                    share|improve this answer























                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      with respect to @Adrian Brand clean answer, here is the solution:



                                      const findMaxStringInArray = (array, lastMax = '' ) => array.reduce((curMax,item)=>typeof item === 'string'?  item.length > curMax.length? item : curMax :  findMaxStringInArray(item, curMax) ,lastMax);





                                      share|improve this answer












                                      with respect to @Adrian Brand clean answer, here is the solution:



                                      const findMaxStringInArray = (array, lastMax = '' ) => array.reduce((curMax,item)=>typeof item === 'string'?  item.length > curMax.length? item : curMax :  findMaxStringInArray(item, curMax) ,lastMax);






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 11 at 6:40









                                      Nirit Levi

                                      2017




                                      2017






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53246122%2ffind-the-longest-string-in-a-nested-array-using-recursion-in-javascript%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Florida Star v. B. J. F.

                                          Danny Elfman

                                          Lugert, Oklahoma