0

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!

SaltyM
  • 93
  • 1
  • 9
  • I'm running this and it works - although I'm using a hardcoded array of strings instead of the `domContainer.find` line. – millerbr Mar 03 '16 at 13:07

5 Answers5

3

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.

tenbits
  • 7,568
  • 5
  • 34
  • 53
1

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.

Steve Greatrex
  • 15,789
  • 5
  • 59
  • 73
1

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 :-)

sba
  • 1,829
  • 19
  • 27
1

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)
georg
  • 211,518
  • 52
  • 313
  • 390
0

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

Community
  • 1
  • 1
Ankit
  • 607
  • 2
  • 9
  • 16