简体   繁体   中英

Get length of longest String in Array

i need to find out the longest string of an array. First of all i push different "text" elements into my array, since the stringe and amount of those "text" elements can differ from case to case. (they are lables of an chart and thus are generated based on the charts sections.

my code right now looks like this:

 var textLengthArray = [];
            domContainer.find(" g > .brm-y-direction > .tick > text").each(function () {
                textLengthArray.push($(this));
            });
            var lgth = 0;
            var longestString;
            for (var i = 0; i < textLengthArray.length; i++) {
                if (textLengthArray[i].length > lgth) {
                    var lgth = textLengthArray[i].length;
                    longestString = textLengthArray[i];
                }
            }

It already pushes all text elements into my array. But when i use

 alert(longestString.length)

i allway get "1" as a result. I am pretty shure i have to add .text anywhere before .length, since the code does not check die textlength of the textelements. Since i am quite new to javascript i would highly appreciate some help.

Thanks in advance!

textLengthArray.push($(this)); should be textLengthArray.push($(this).text()); otherwise your array consists of jQuery objects. And indeed jQuerySet has length property. And in your case the set consists of 1 element.

You are re-declaring lgth in each iteration of the array which is re-assigning the value.

Replace var lgth = textLengthArray[i].length with lgth = textLengthArray[i].length and you should be good.

I don't know about the rest of your code, looks fine. But you're pushing a jQuery object $(this) , not a string. Line three should read textLengthArray.push(this); .

Apparently one of the strings your pushing is a valid jQuery selector that finds an element :-)

No need to create a separate array. Just iterate objects and update as you go:

 longest = ""; $('div').each(function() { var t = $(this).text(); if(t.length > longest.length) longest = t; }); alert(longest) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>hello</div> <div>wonderful</div> <div>world</div> 

To get the longest string from any array, try reduce :

 a = ['hello', 'wonderful', 'world'] longest = a.reduce(function(prev, e) { return prev.length >= e.length ? prev : e; }); alert(longest) 

Sort the array by length and get the first element. Hope it works for you

stackoverflow.com/questions/10630766/sort-an-array-based-on-the-length-of-each-element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM