Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 331
ditto Avatar asked Jul 12 '15 08:07

ditto


People also ask

How do you sort an array of objects based on ID?

IF you mean that you wanted them sorted by id and if the id matches, you want them sorted by name then use this: items. sort(function(a, b) { if (a.id !== b.id) { return a.id - b.id } if (a.name === b.name) { return 0; } return a.name > b.name ?

How do you sort values in HTML?

Adding the “sortable” class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work. The <th> tag defines a header cell in an HTML table.


2 Answers

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

like image 175
TaoPR Avatar answered Sep 21 '22 15:09

TaoPR


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

like image 44
vorillaz Avatar answered Sep 18 '22 15:09

vorillaz