0

I have 2 blocks of code and search for a longest string in each block appearing on each alert. obviously, wonderful is longest string in the block 1 and beautiful is longest string in block 2.

wonderful should be in first alert and beautiful should be in second alert, but somehow I miss something. Please give me a hand.

Thanks!

$('.parent').each(function() {
  longest = "";
  $('.child').each(function() {
    var textChild = $(this).text();
    if (textChild.length > longest.length) {
      longest = textChild;
    }
  });
  alert(longest)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="child">hello</div>
  <div class="child">wonderful</div>
  <div class="child">world</div>
</div>

<div class="parent">
  <div class="child">hello</div>
  <div class="child">beautiful</div>
  <div class="child">world</div>
</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
abcid d
  • 2,821
  • 7
  • 31
  • 46

1 Answers1

0

To do what you require you can use map() to build an array of the text content of the .child elements within each .parent, then you can use reduce() to get the longest of them.

Note that you need to output the longest value within the loop. Try this:

$('.parent').each(function() {
  let longest = $(this).find('.child').map((i, el) => el.textContent.trim()).get().reduce((a, b) => a.length > b.length ? a : b);
  console.log(longest);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="child">hello</div>
  <div class="child">wonderful</div>
  <div class="child">world</div>
</div>

<div class="parent">
  <div class="child">hello</div>
  <div class="child">beautiful</div>
  <div class="child">world</div>
</div>

If you want to get the longest values outside of the loop, then I'd suggest pushing them to their own array which you can iterate through as required.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339