[英]Sorting list items by data attribute, alphabetically and then numerically
I'm wanting to sort this list from AZ and then 0-9. 我想从AZ排序这个列表,然后是 0-9。
<ol class="columns">
<li data-char="y">y</li>
<li data-char="1">1</li>
<li data-char="a">a</li>
<li data-char="e">e</li>
<li data-char="c">c</li>
<li data-char="w">w</li>
<li data-char="0">0</li>
<li data-char="9">9</li>
<li data-char="g">g</li>
</ol>
$(".columns li").sort(sort_li).appendTo('.columns');
function sort_li(a, b){
return ($(b).data('char')) < ($(a).data('char')) ? 1 : -1;
}
Having looked at similar questions, this was what I came up with, but it only works with numbers or letters (not both). 看了类似的问题,这就是我想出的,但它只适用于数字或字母(不是两者)。 https://jsfiddle.net/qLta1ky6/
https://jsfiddle.net/qLta1ky6/
ASCII codes of digits are smaller than alphabets, so just simply add weight to them when doing comparison like this: 数字的ASCII码小于字母,所以在进行比较时只需添加权重,如下所示:
$(".columns li").sort(sort_li).appendTo('.columns');
function sort_li(a, b){
var va = $(a).data('char').toString().charCodeAt(0);
var vb = $(b).data('char').toString().charCodeAt(0);
if (va < 'a'.charCodeAt(0)) va += 100; // Add weight if it's a number
if (vb < 'a'.charCodeAt(0)) vb += 100; // Add weight if it's a number
return vb < va ? 1 : -1;
}
A regular sorting process will map the numeric values first. 常规排序过程将首先映射数值。 My thought is about sorting and after that processing the arrays to achieve the desired result.
我的想法是关于排序和处理数组后,以达到预期的结果。
var items = $('.columns li').get();
items.sort(function(a,b){
var keyA = $(a).attr("data-char");
var keyB = $(b).attr("data-char");
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
//split the array to integers and alphanumerics
var nums = [], alphas = [];
$.each(items,function(i,v){
if(isNaN(parseFloat($(v).attr("data-char"))))
alphas.push(v)
else
nums.push(v)
});
items = alphas.concat(nums)
var ul = $('.columns');
$.each(items, function(i, li){
ul.append(li);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.