JQuery Sort Array of DOM Objects based off DOM val

2020-08-01 02:00发布

问题:

I've been using Jquery for a couple of years but this question pushes my limits.

I have an Array of DOM Objects that I'm sorting based of a number of conditions. I create the array like this:

var conversationsInBoxMemberUserIDsArray = $('#conversationsInBoxMessagesWrapperDIV').children().map(function() {return $(this);}).get();

Each item pushed onto the array is a section of DOM. Or a reference to a section of DOM could be a better way to say it. I can see this it refers to a section of DOM because when I change the order and append this array back to the root DIV the order of all the objects (DIV's with content) within changes visually. The section of DOM likes this (cut down version to save time/space):

<divContainer>
  <div_sub1>
    <div sub2>
      <h3 class="name">Adam</h3>
    </div>
  </div>
</div>

I want to sort this array of DOM objects based off the DOM element.text value with class $(.name)

eg: A-Z based off this this text value of name - eg: Adam before Ben

Is this possible?

Can this be done using the standard sort function:

theArray.sort(function(a, b){
   if (a.Field2 == b.Field2) return 0;
   if (a.Field2 < b.Field2) return -1;
   return 1;
 });

any advice would be greatly appreciated. Will also need to do the same off a unix timestamp.

adam

回答1:

Try something like

var $ct = $('#container'),
    $items = $ct.children(),
    array = $items.get();

array.sort(function (o1, o2) {
    return $(o1).find('.header h3').text().localeCompare($(o2).find('.header h3').text())
});

$ct.append(array)

Demo: Fiddle


After doing some caching of values, you can try

var $ct = $('#container'),
    $items = $ct.children(),
    array = $items.map(function () {
        var $this = $(this);
        $this.data('header', $.trim($this.find('.header h3').text()))
        return $this;
    }).get();

array.sort(function (o1, o2) {
    return o1.data('header').localeCompare(o2.data('header'))
});

$ct.append(array)

Demo: Fiddle



回答2:

You can do it like this:

var arr_children_to_sort = $('div').children(...);

arr_children_to_sort.sort(function(a, b) {
    if ($(a).find('h3').hasClass('name')) {
        if ($(b).find('h3').hasClass('name')) {
            return (($(a).find('h3').text() >= $(b).find('h3').text()) ? 1 : -1);
        }
        return 1;
    }
    else if ($(b).find('h3').hasClass('name')) {
        return -1;
    }

    return 0;
});

Just switch up the values of the return statements to set the actual order you need.