Sort images based on data attribute

I’m trying to sort the following images based on their data-card attribute:

<div id="deck-area">
    <div class="deck-area-cards">
    <span class="deck-img-container"><img class="cardimg" onclick="removeCard(this,'BT1-010','Red')" src="https://images.digimoncard.io/images/cards/BT1-010.jpg" data-card="BT1-010" data-id="1" title="Agumon - BT1-010"></span>
    <span class="deck-img-container"><img class="cardimg" onclick="removeCard(this,'BT2-033','Yellow')" src="https://images.digimoncard.io/images/cards/BT2-033.jpg" data-card="BT2-033" data-id="1" title="Agumon - BT2-033"></span>
    <span class="deck-img-container"><img class="cardimg" onclick="removeCard(this,'BT1-010','Red')" src="https://images.digimoncard.io/images/cards/BT1-010.jpg" data-card="BT1-010" data-id="1" title="Agumon - BT1-010"></span>
    </div>
</div>

I’ve been targeting the images in jQuery like so: ('#deck-area .deck-area-cards .deck-img-container img') and then attempting to sort using the following sort option:

  jQuery('#deck-area .deck-area-cards .deck-img-container img').sort(function(a, b) {
    return jQuery(b).data('card') - jQuery(a).data('card');
  }).appendTo('#deck-area .deck-area-cards .deck-img-container'); 

However, this method seems to add 3 of each to each instance of .deck-img-container. I’m a little out of ideas with this. I’ve tried a couple of different targetting methods for appendTo but can’t seem to get it right.

Answer

const wrapper = jQuery('#deck-area .deck-area-cards .deck-img-container').toArray(); 

const imgArr  =jQuery('#deck-area .deck-area-cards .deck-img-container img')

const newArr = imgArr.sort(function(a, b) {
  return jQuery(b).data('card') > jQuery(a).data('card') ? -1 :1
})


wrapper.forEach((wrap,idx)=>{
  jQuery(wrap).html(newArr[idx])
})

Leave a Reply

Your email address will not be published. Required fields are marked *