Get highest string length in an array

Discussion in 'JavaScript' started by Silver89, Dec 8, 2009.

  1. #1
    Is it possible to get the highest string length within an array? I tried looking for a sort function but this doesn't seem to exist.
     
    Silver89, Dec 8, 2009 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    you'd have to walk it
    
    var maxLength = function(array) {
        var ml = 0, al = array.length;
        while(al--) {
            ml = array[al].length > ml ? array[al].length : ml;
        }
        return ml;
    };
    
    words: [
            "guitar",
            "cello",
            "piano",
            "drums",
            "violin",
            "clarinet",
            "saxophone",
            "trombone",
            "bassoon",
            "piccolo",
            "oboe",
            "bagpipe",
            "bugle",
            "trumpet",
            "trombone",
            "tuba",
            "accordion",
            "harp",
            "harmonica",
            "recorder",
            "banjo",
            "sitar",
            "fiddle",
            "mandolin",
            "trombone",
            "bongo",
            "snare",
            "timpani",
            "trombone",
            "cowbell",
            "gong",
            "maraca",
            "tambourine",
            "triangle",
            "xylophone",
            "synthesizer",
            "theremin",
            "organ",
            "keytar"
    ];
    
    alert(maxLength(words)); // 11
    
    Code (javascript):
     
    dimitar christoff, Dec 8, 2009 IP