Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i make .each() function result by array to join a single array result by jQuery?

i just want to compare each value in array. and get high value.
but i have no idea to convert a single array.

here is the code ::

wrap.each((index)=> {


        const year = wrap.eq(index).find('.year'),
              list = wrap.eq(index).find('.list'),
              line = wrap.eq(index).children('.line'),
              picker = wrap.eq(index).find('.line span');

            let btnWidth = [list.width()];

            var arr = [];
            arr.push(btnWidth);

            console.log(arr)

      }); 

this result is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[724]

[759]

[687]

[483]

like this but i want make to

[724, 759, 687, 483]

>Solution :

The issue is you define arr as a new, empty array within each .each() iteration.

You can use jQuery’s .map() method to convert an element collection to an array of values

const wrap = $(".wrap");
const widths = wrap.map((_, elt) => $(elt).find(".list").width()).get();

console.log(widths);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<ul><li class="wrap"><p class="list" style="width:724px">724px</p></li><li class="wrap"><p class="list" style="width:759px">759px</p></li><li class="wrap"><p class="list" style="width:687px">687px</p></li><li class="wrap"><p class="list" style="width:483px">483px</p></li></ul>

And of course, you might not need jQuery

const wrap = document.querySelectorAll(".wrap");
const widths = Array.from(
  wrap,
  (elt) => elt.querySelector(".list")?.offsetWidth
);

console.log(widths);
<ul><li class="wrap"><p class="list" style="width:724px">724px</p></li><li class="wrap"><p class="list" style="width:759px">759px</p></li><li class="wrap"><p class="list" style="width:687px">687px</p></li><li class="wrap"><p class="list" style="width:483px">483px</p></li></ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading