Hello, there is a task to sort the blocks by the data-attribute, for example, there is the source code:

<div data-sort="one">123</div> <div data-sort="three">345</div> <div data-sort="three">3534</div> <div data-sort="two">56546</div> <div data-sort="one">546546</div> 

After processing the plugin, it is necessary to obtain the following result:

 One <div data-sort="one">123</div> <div data-sort="one">546546</div> Two <div data-sort="two">56546</div> Three <div data-sort="three">345</div> <div data-sort="three">3534</div> 

I just want a plugin for this to connect, preferably with a callback api, so that the handlers are not reset

    1 answer 1

     var obj = { one: 1, two: 2, three: 3 }; $("[data-sort]").get().sort(function(a, b) { return obj[a.dataset.sort] - obj[b.dataset.sort] || a.textContent - b.textContent }).reduce(function(o, el) { var d = el.dataset.sort; if (!o[d]) { $("body").append(d); o[d] = true } $("body").append(el); return o }, {}); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div data-sort="one">123</div> <div data-sort="three">345</div> <div data-sort="three">3534</div> <div data-sort="two">56546</div> <div data-sort="one">546546</div>