christopherhill
10/6/2013 - 4:25 PM

Find the longest string in a given array.

Find the longest string in a given array.

function longestString(i) {
    
    // i will be an array.
    // return the longest string in the array
    
    var longestIndex = -1;
    
    for (var j = 0; j < i.length; j++) {
     
        var curStr = i[j];
        var maxStr = longestIndex > -1 ? i[longestIndex] : '';
        
        if (typeof(curStr) === 'string') {
          if (curStr.length > maxStr.length) {
            longestIndex = j;
          } 
        } 
    }

    return i[longestIndex];

}