简体   繁体   中英

Sort element by two data attributes using jquery sort

I have an li element with 2 data attributes, basically I want to sort out first the data-arrange attribute, this is the element

 <ul>
        <li data-arrange="2" data-rdays="100">John</li>
        <li data-arrange="1" data-rdays="300">Paul</li>
        <li data-arrange="1" data-rdays="500">Bryan</li>
        <li data-arrange="3" data-rdays="240">Mark</li>
        <li data-arrange="3" data-rdays="500">Victor</li>
        <li data-arrange="4" data-rdays="200">Tess</li>
    </ul>

so from the given element it should return like this

data-arrange attribute value arrangement

    1 
    1
    2
    3
    3
    4

then I want to sort it with data-rdays attribute from highest to lowest based on data-arrange attribute arrangement so it will look like something like this

1 500
1 300
2 100
3 500
3 240
4 200

result should be like this

Bryan
Paul
John
Victor
Mark
Tess

This is what I've tried so far:

function sort_li(a, b){
        return ($(b).data('arrange')) < ($(a).data('arrange')) ? 1 : -1; 

  /* Other return staments that I've tried
      return ($(a).data('rdays') && $(b).data('arrange')) < ($(b).data('rdays') 
      && $(a).data('arrange')) ? 1 : -1;     
     return new Date($(a).data("date")) - new Date($(b).data("date")); */

     }   

Is there a way how can I accomplish this? Thank you.

You can first sort on arrange data and for the data with same arrange data sort on rdays data using array#sort .

 $(function() { $("ul li").sort((a,b) => { return $(a).data('arrange') - $(b).data('arrange') || $(b).data('rdays') - $(a).data('rdays'); }).appendTo('ul'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li data-arrange="2" data-rdays="100">John</li> <li data-arrange="1" data-rdays="300">Paul</li> <li data-arrange="1" data-rdays="500">Bryan</li> <li data-arrange="3" data-rdays="240">Mark</li> <li data-arrange="3" data-rdays="500">Victor</li> <li data-arrange="4" data-rdays="200">Tess</li> </ul> 

This should sort first on the arrange attribute in ascending order and then on the rdays attribute in descending order.

function sort_li(a, b) {
    const arrangeA = +($(a).data('arrange');
    const arrangeB = +$(b).data('arrange');

    if (arrangeA !== arrangeB) {
        // sort arrange in ascending order
        return arrangeA < arrangeB ? -1 : 1;
    }

    const rdaysA = +($(a).data('rdays');
    const rdaysB = +$(b).data('rdays');

    if (rdaysA !== rdaysB) {
        // sort rdays in descending order
        return rdaysA > rdaysB ? -1 : 1;
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM