PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

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

 November 02, 2022     arrays, each, indexing, javascript, jquery     No comments   

Issue

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]


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>



Answered By - Phil
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing