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

Time:10-20

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

[724]

[759]

[687]

[483]

like this but i want make to

[724, 759, 687, 483]

CodePudding user response:

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 ><p  style="width:724px">724px</p></li><li ><p  style="width:759px">759px</p></li><li ><p  style="width:687px">687px</p></li><li ><p  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 ><p  style="width:724px">724px</p></li><li ><p  style="width:759px">759px</p></li><li ><p  style="width:687px">687px</p></li><li ><p  style="width:483px">483px</p></li></ul>

  • Related