ditto
ditto

Reputation: 6277

Sorting list items by data attribute, alphabetically and then numerically

I'm wanting to sort this list from A-Z and then 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/

Upvotes: 5

Views: 1108

Answers (2)

vorillaz
vorillaz

Reputation: 6276

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);
});

Demo

Upvotes: 1

TaoPR
TaoPR

Reputation: 6052

ASCII codes of digits are smaller than alphabets, so just simply add weight to them when doing comparison like this:

$(".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;   
}

Updated JSFiddle here

Upvotes: 5

Related Questions