Giter Club home page Giter Club logo

tinysort's Introduction

TinySort

TinySort is a small script that sorts DOM elements. It sorts HTMLElements by text- or attribute value, or by that of one of its children. The examples below should help getting you on your way.

If you find a bug, have a feature request or a code improvement you can file them here. Please provide code examples where applicable.

TinySort used to be a jQuery plugin but was rewritten to remove the jQuery dependency. It is now smaller *and* faster (and has no dependencies). Functionality is the same but changes have been made to the parameters and options.

usage

The first (and only required) argument is a NodeList, an array of HTMLElements or a string (which is converted to a NodeList using document.querySelectorAll).

tinysort(NodeList);

The other arguments can be an an options object.

tinysort(NodeList,{place:'end'});

If the option object only contains a selector you can suffice by using the selector string instead of the object.

tinysort(NodeList,'span.surname');

For multiple criteria you can just overload.

tinysort(NodeList,{selector:'.surname'},{selector:'.name'},{data:'age'});

Default settings can be changed

tinysort.defaults.order = 'desc';
tinysort.defaults.attr = 'title';

options

The options object can have the following settings:

options.selector (string=undefined) A CSS selector to select the element to sort to.

options.order (string='asc') The order of the sorting method. Possible values are 'asc', 'desc' and 'rand'.

options.attr (string=null) Order by attribute value (ie title, href, class)

options.data (string=null) Use the data attribute for sorting.

options.place (string='org') Determines the placement of the ordered elements in respect to the unordered elements. Possible values 'start', 'end', 'first', 'last' or 'org'.

options.useVal (boolean=false) Use element value instead of text.

options.cases (boolean=false) A case sensitive sort (orders [aB,aa,ab,bb])

options.natural (boolean=false) Use natural sort order.

options.forceStrings (boolean=false) If false the string '2' will sort with the value 2, not the string '2'.

options.ignoreDashes (boolean=false) Ignores dashes when looking for numerals.

options.sortFunction (function=null) Override the default sort function. The parameters are of a type {elementObject}.

options.useFlex (boolean=true) If one parent and display flex, ordering is done by CSS (instead of DOM)

options.emptyEnd (boolean=true) Sort empty values to the end instead of the start

options.console (boolean=undefined) an optional console implementation to prevent output to console

examples

default sorting

The default sort simply sorts the text of each element

tinysort('ul#xdflt>li');

sort on any node

TinySort works on any nodeType. The following is a div with spans.

tinysort('div#xany>span');

sorted numbers

TinySort also works on numbers.

tinysort('ul#xnum>li');

mixed literal and numeral

In a normal sort the order would be a1,a11,a2 while you'd really want it to be a1,a2,a11. TinySort corrects this:

tinysort('ul#xmix>li');

sorted by attribute value

Sort by attribute value by adding the 'attr' option. This will sort by attribute of, either the selection, or of the sub-selection (if provided). In this case sort is by href on the anchor sub-selection.

tinysort('ul#xval>li',{selector:'a',attr:'href'});

Another example: images sorted by attribute title value.

tinysort('div#ximg>img',{attr:'title'});

sorted by sub-selection

You can provide an additional subselection by setting the selector option. If no other options are set you can also just pass the selector string instead of the options object.

In this example the list elements are sorted to the text of the second span.

tinysort('ul#xsub>li','span:nth-child(2)');

The following example will only sort the non-striked elements.

tinysort('ul#xattr>li','span:not([class=striked])');

return only sorted elements

By default, all the elements are returned, even the ones excluded by your sub-selection. By parsing the additional parameter 'returns=true' only the sorted elements are returned. You can also adjust the placement of the sorted values by adding the 'place' attribute. In this case the original positions are maintained.

tinysort('ul#xret>li','span:not([class=striked])',{returns:true,place:'org'})
    .forEach(function(elm){
        elm.style.color = 'red';
    })
;

multiple sort criteria

Sometimes multiple sorting criteria are required. For instance: you might want to sort a list of people first by surname then by name.

For multiple sorting rules you can just overload the parameters. So tinysort(selector,options) becomes tsort(selector,options1,options2,options3...). Note that in the next example the second parameter 'span.name' will be rewritten internally to {selector:'span.name'}.

tinysort('ul#xmul>li','span.name',{selector:'span.date',data:'timestamp'});

non-latin characters

A normal array sorts according to Unicode, which is wrong for most languages. For correct ordering you can use the charorder plugin to parse a rule with the 'charOrder' parameter. This is a string that consist of exceptions, not the entire alfabet. For characters that should sort equally use brackets. For characters that consist of multiple characters use curly braces. For example:

  • cčć sorts c č and ć in that order

  • æøå in absence of a latin character æ ø and å are sorted after z

  • ι[ίϊΐ] ί ϊ and ΐ are sorted equally to ι

  • d{dž} dž is sorted as one character after d

  • å[{Aa}] Aa is sorted as one character, equal to å, after z

Here some real examples:

tinysort('ul#greek>li',{charOrder:'α[ά]βγδε[έ]ζη[ή]θι[ίϊΐ]κλμνξο[ό]πρστυ[ύϋΰ]φχψω[ώ]'});
tinysort('ul#danish>li',{charOrder:'æøå[{Aa}]'});
tinysort('ul#serb>li',{charOrder:'cčćd{dž}đl{lj}n{nj}sšzž'});

Here are some example languages:

Language charOrder
since only one of these is my native language please feel free to contact me if you think corrections are in order
Cyrilicабвгдђежзијклљмнњопрстћуфхцчџш
Czecha[á]cčd[ď]e[éě]h{ch}i[í]n[ň]o[ó]rřsšt[ť]u[úů]y[ý]zž
Danish and Norwegianæøå[{Aa}]
Dutcha[áàâä]c[ç]e[éèêë]i[íìîï]o[óòôö]u[úùûü]
Frencha[àâ]c[ç]e[éèêë]i[ïî]o[ôœ]u[ûù]
Germana[ä]o[ö]s{ss}u[ü]
Greekα[ά]βγδε[έ]ζη[ή]θι[ίϊΐ]κλμνξο[ό]πρστυ[ύϋΰ]φχψω[ώ]
Icelandica[á]dðe[é]i[í]o[ó]u[ú]y[ý]zþæö
Polishaąbcćeęlłnńoósśuúzźż
Russianабвгдеёжзийклмнопрстуфхцчшщъыьэюя
Serbo-Croatiancčćd{dž}đl{lj}n{nj}sšzž
Spanisha[á]c{ch}e[é]i[í]l{ll}nño[ó]u[ú]y[ý]
Swedishåäö

natural sorting

Machines read differently than you do. Natural sorting makes your machine more like you by enabling it to differentiate between numeric values within a string.

tinysort('ul#xnat>li',{natural:true});

sort by value

The value property is primarily used to get the values of form elements, but list-elements also have the value property. By setting the useVal option you can also sort by this form element value.

tinysort('ul#xinp>li',{selector:'input',useVal:true});

sort by data

Sort by data attribute by setting the data option.

tinysort('ul#xdta>li',{selector:'a',data:'foo'});

sorted descending

Sort in ascending or descending order by setting the order option to asc or desc.

tinysort('ul#xdesc>li',{order:'desc'});

randomize

TinySort can also order randomly (or is that a contradiction).

tinysort('ul#xrnd>li',{order:'rand'});

custom sort function

Custom sort functions are similar to those you use with regular Javascript arrays with the exception that the parameters a and b are objects of a similar type {elementObject}, an object with the following properties:

  • elm {HTMLElement}: The element
  • pos {number}: original position
  • posn {number}: original position on the partial list

When you use the custom sort function all other properties will be ignored because it expects a custom implementation.

tinysort('ul#xcst>li',{sortFunction:function(a,b){
var lenA = a.elm.textContent.length
    ,lenB = b.elm.textContent.length;
return lenA===lenB?0:(lenA>lenB?1:-1);
}});

sorting tables

With a little extra code you can create a sortable table:

var table = document.getElementById('xtable')
    ,tableHead = table.querySelector('thead')
    ,tableHeaders = tableHead.querySelectorAll('th')
    ,tableBody = table.querySelector('tbody')
;
tableHead.addEventListener('click',function(e){
    var tableHeader = e.target
        ,textContent = tableHeader.textContent
        ,tableHeaderIndex,isAscending,order
    ;
    if (textContent!=='add row') {
        while (tableHeader.nodeName!=='TH') {
			tableHeader = tableHeader.parentNode;
		}
        tableHeaderIndex = Array.prototype.indexOf.call(tableHeaders,tableHeader);
        isAscending = tableHeader.getAttribute('data-order')==='asc';
        order = isAscending?'desc':'asc';
        tableHeader.setAttribute('data-order',order);
        tinysort(
            tableBody.querySelectorAll('tr')
            ,{
                selector:'td:nth-child('+(tableHeaderIndex+1)+')'
                ,order: order
            }
        );
    }
});
word int float mixed add row

animated sorting

Tinysort has no built in animating features but it can quite easily be accomplished through regular js/jQuery.

<style type="text/css"> ul#xanim { position: relative; display: block; } ul#xanim li { transition: top 500ms; -webkit-transition: top 500ms; } </style>
var ul = document.getElementById('xanim')
	,lis = ul.querySelectorAll('li')
	,liHeight = lis[0].offsetHeight
;
ul.style.height = ul.offsetHeight+'px';
for (var i= 0,l=lis.length;i<l;i++) {
	var li = lis[i];
	li.style.position = 'absolute';
	li.style.top = i*liHeight+'px';
}
tinysort('ul#xanim>li').forEach(function(elm,i){
    setTimeout((function(elm,i){
        elm.style.top = i*liHeight+'px';
    }).bind(null,elm,i),40);
});

tinysort's People

Contributors

dependabot[bot] avatar drvic10k avatar igoradamenko avatar mroswell avatar psolom avatar rjvdboon avatar sjeiti avatar tetsuo13 avatar wooly avatar xdml avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tinysort's Issues

JQuery Mobile Autodividers

I might be doing something wrong, but when I try to use tinysort to sort a listview using jquerymobile and auto-dividers are enabled, the sort doesn't work properly. Without autodividers, I don't have a problem.

Settings "returns" does the same for true and false

Setting the "returns" setting to true, always returns all of the li's even
if nothing was sorted, on version 1.0.4

Migrated from http://code.google.com/p/tinysort/issues/detail?id=2


earlier comments

sjeiti said, at 2011-06-17T20:41:56.000Z:

Nope, don't see it. Please provide an example.

sjeiti said, at 2011-08-02T09:36:41.000Z:

Oh I think I see your pov. If you sort a nodelist it will always sort, even though they are already in the correct order. Only when you provide a subselection as a first parameter the return parameter will work, returning only the nodes the subselection applies to. So $('li').sort('p.foo',{return:true}) will only return the list elements that contain a paragraph with the class 'foo'.

The functionality you expect would be a bit trifle to implement. For instance if you sort [4,0,1,2,3] would you only return [4] or [0,1,2,3,4] (since none of the positions match the original one).
So I think it's better to keep it outside the scope of the plugin.

(I did find a related issue where $.filter instead of $.find should be used for the subselection)

Negative values not supported?

Hi,

As far as I can see, negative attribute values are interpreted as text, not numbers.

http://jsfiddle.net/VwKL6/

Thanks for a great plugin!

  • John

    Migrated from http://code.google.com/p/tinysort/issues/detail?id=24


    earlier comments

    jwarren.carroll said, at 2012-03-10T04:52:14.000Z:

    I have also run into this. While in my scenario it would appear that sorting starts over for negative numbers. If I have a list sorted descending, it properly shows the positive number largest first. However, once you get below zero, it will show the smallest negative numbers first (largest absolute value).

Example:

100
50
10
0
-100
-50
-10

jwarren.carroll said, at 2012-03-10T04:56:16.000Z:

Ok, after reviewing it further, it does appear that they are sorted as string values.

sjeiti said, at 2012-03-10T17:15:40.000Z:

Hi, havent had time yet to look into this but at first glance I suspect the culprit is the regex named 'rxLastNr' (that should but doesnt includethe minus sign). I'll try and see if I can fix it soon.

sjeiti said, at 2012-03-10T19:22:35.000Z:

Small bug.. two extra characters fixed it: http://jsfiddle.net/Sjeiti/w5Seh/ I dont know when Ill be able to commit/release this since Im not behind a computer any time soon. So for now just use this uncompressed version: http://tinysort.sjeiti.com/scripts/jquery.tinysort.i24.js

jseverinson said, at 2012-03-11T11:33:28.000Z:

I'm impressed! Well done and thanks again for the great script!

sjeiti said, at 2012-03-13T16:21:05.000Z:

This issue was closed by revision r23.

sjeiti said, at 2012-08-17T15:24:29.000Z:

This issue was closed by revision 536bc25.

Array.indexOf undefined in MSIE 8.0

Array.indexOf seems to be undefined in the Internet Explorer 8.0

Fix:
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}

Source: http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/

Migrated from http://code.google.com/p/tinysort/issues/detail?id=26


earlier comments

reubensrj said, at 2012-03-27T11:55:41.000Z:

It looks like a null array will not have indexOf defined. So check if array is empty before the indexOf call captures the error.

if (aAllChars.length > 0 && aAllChars.indexOf(s)!==-1) aAllChars.push(s);

mcpatten said, at 2012-06-13T19:37:05.000Z:

FYI: You might want to consider using the ECMA-262 standard version of this method, which is available @ https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

the sort plugin can support target?

the sort plugin can insert a target when get result?
support parameter such as "target"

oh i'm forget said : when sort value is 'undefined' or '' ,the sort plugin is an error action
my english is very pool--!

Can't sort dynamically added DOM elements

I could just be doing it wrong, because I'm new to jQuery, but I have a set of elements that have a <time> tag and want to sort on those elements. This works great for the elements that are in the HTML file loaded. However, I'm also loading more via jQuery. In this particular case, I have say list of blog entries and I want to sort some tweets to be chronologically accurate. The sort does't apply to the tweets because they were loaded after the page was loaded (but before I called sort).

Is there some way to sync the dom so that tsort() will find the "new" DOM elements?

Migrated from http://code.google.com/p/tinysort/issues/detail?id=17


earlier comments

sjeiti said, at 2011-10-12T22:13:07.000Z:

Please note that 'issues' is not a forum where you can post issues with your own code but a list where you can file bug reports.

If you'd read the code of the provided examples you'd have seen that they are all sorts on dynamically added elements.

I can't say for sure what you're doing wrong since you didn't provide any code but what might be the case is that you declare your jQuery variable in advance, add elements, and then try to sort with your earlier declared jQuery variable. You must redeclare your jQuery variable: a jQuery object does not notice any changes in DOM.

Good luck :-)

derek.ditch said, at 2011-10-12T22:45:16.000Z:

Thanks. That makes sense. Sorry for opening an 'issue' for something that isn't. You might add that to the documentation since newcomers to jQuery (such as myself) may not know that jQuery objects don't notice changes. It seemed evident to me after fighting this for sometime, but it wasn't clear how to fix it (nor were Google searches successful in giving me this answer).

It really didn't make sense that this wouldn't work on dynamic elements since if it the element wasn't dynamic, it could just be sorted on the server side. Thanks for a great library and keep up the good work ;-)

$.data with numeric values break

As demonstrated with http://jsfiddle.net/xXSZB/2/ ,

$.data sorts well for strings, but will break on a number, giving error "Object /n/ has no method 'match'"

This occurs on line 205 with code:
var aAnum = sA&&sA.match(rxLastNr)

Using Chrome 18.0.1025.142
on Ubuntu Linux
with any jQuery version.

Possible workarounds -

  1. var aAnum = sA && (""+sA).match(rxLastNr)
  2. var aAnum = sA && prsflt(sA) == sA

Migrated from http://code.google.com/p/tinysort/issues/detail?id=27

Fix for some IE8 Problems

I was having some trouble using TinySort in IE8. On line 232 and in the for loop that starts directly below the 232 block. I am not really sure what is happening in this code block but the checks I added appeared to fix the problem in IE8, FF, and Chrome. I added some simple if checks around this code and it appeared to fix the problem in IE8. I figured I'd throw this code up in case you'd like to add it to the main branch, I'd be curious to know what the root cause of the problem was here, or if this fix will cause any other problems with tinysort.

for (j in aElements) {
//undefined check added here
                if (aElements[j] !== undefined && aElements[j].s !== undefined) {
                    aElements[j].s.sort(fnSort);
                }

            }
            //
            // order elements and fill new order

            for (j in aElements) {
//undefined check added here
                if (aElements[j] !== undefined && aElements[j].s !== undefined) {
                    var oParent = aElements[j]
                        ,iNumElm = oParent.s.length
                        ,aOrg = [] // list for original position
                        ,iLow = iNumElm
                        ,aCnt = [0,0] // count how much we've sorted for retreival from either the sort list or the non-sort list (oParent.s/oParent.n)
                    ;
                    switch (oSettings.place) {
                        case 'first':   $.each(oParent.s,function(i,obj) { iLow = mathmn(iLow,obj.n) }); break;
                        case 'org':     $.each(oParent.s,function(i,obj) { aOrg.push(obj.n) }); break;
                        case 'end':     iLow = oParent.n.length; break;
                        default:        iLow = 0;
                    }
                    for (i=0;i<iNumElm;i++) {
                        var bSList = contains(aOrg,i)?!fls:i>=iLow&&i<iLow+oParent.s.length
                            ,mEl = (bSList?oParent.s:oParent.n)[aCnt[bSList?0:1]].e;
                        mEl.parent().append(mEl);
                        if (bSList||!oSettings.returns) aNewOrder.push(mEl.get(0));
                        aCnt[bSList?0:1]++;
                    }
                }
            }
            oThis.length = 0;
            Array.prototype.push.apply(oThis,aNewOrder);
            return oThis;

IE 8 Error

This line of code caused grief with IE.

"if (!~aAllChars.indexOf(s)) aAllChars.push(s);"

Because I didn't need that functionality, I just removed it myself.

Migrated from http://code.google.com/p/tinysort/issues/detail?id=25


earlier comments

sjeiti said, at 2012-03-13T16:21:05.000Z:

This issue was closed by revision r23.

zaunseder said, at 2012-03-16T08:34:50.000Z:

The indexOf method is causing problems in IE8 also in the new revision. I changed it to use the jQuery Method "inArray":

if ($.inArray(s, aAllChars)!==-1) aAllChars.push(s);

Then IE8 is sorting like normal.

[email protected] said, at 2012-06-20T20:00:51.000Z:

thanks "zaunse" that worked for me (IE9 in IE7 Compat)..

I modified my min file with:

if(b.inArray(k,a)!==-1){a.push(k)}

sjeiti said, at 2012-08-17T15:24:30.000Z:

This issue was closed by revision 536bc25.

tinysort not working with jquery 1.5 (t.s is undefined)?

I am using tinysort on a page and I updated jQuery to 1.5.1 and now I get the "t.s is undefined" error. Is this because tinysort is not compatible with jquery 1.5.1 or do I need to modify my code?

Migrated from http://code.google.com/p/tinysort/issues/detail?id=10


earlier comments

rustning said, at 2011-03-09T08:14:49.000Z:

If I use the full version instead of the minified, the error is "a.s is undefined" on row 75 (var x = a.s.toLowerCase ? a.s.toLowerCase() : a.s;)

sjeiti said, at 2011-06-17T21:32:56.000Z:

I've seen this before but can't reproduce. Could you post an example? (http://jsfiddle.net/)

emo1313 said, at 2011-08-01T07:37:46.000Z:

greeting, I am having exactly the same issue t.s undefined but on line 12 here is the code calling

var sortabc = $('<a href="javascript:void(0)" class="sortbtn">Sort by tag name</a><br>').toggle(
    function() {
        $("#tag_cloud ul li").tsort({order:"asc",attr:"name"});
    },
    function() {
        $("#tag_cloud ul li").tsort({order:"desc",attr:"name"});
    }

the target is alist of tags. site is nsfw so I'll omit a link, sorry :/

Cheers.

emo1313 said, at 2011-08-01T09:07:40.000Z:

ok I think I figured my problem out.

the ul is inside a div is i call sort on the ul it craps out however if i call it on the div parents id it works as advertised.

sjeiti said, at 2011-08-02T10:07:02.000Z:

I've tried to replicate this and I only get the specific error when I deliberately insert an error. For instance calling $.tsort({attr:'name'}) while one of the nodes does not contain a name attribute.

So the errors are human ones, but I'll build in a check so it will silently fail instead of throwing an actual error.

sjeiti said, at 2011-08-02T10:07:33.000Z:

Issue 6 has been merged into this issue.

Add support for sorting by data

Out of necessity I've hacked my copy (literally 2 lines of code) to be able to take a data option (as in .data() ), exactly the same way it works for attr. I think it would be a useful feature for the project

Migrated from http://code.google.com/p/tinysort/issues/detail?id=14


earlier comments

sjeiti said, at 2011-08-02T12:37:38.000Z:

excellent idea

Tinysort not working with Jquery 1.4.2

I've tried using the new JQuery version with tinysort but it seems to not work.
When used it returns this error

this.setArray is not a function:
(function(B){B.tinysort={id:"TinySort"...rt=B.fn.tsort=B.fn.tinysort})(jQuery);

Migrated from http://code.google.com/p/tinysort/issues/detail?id=3


earlier comments

bibendus1983 said, at 2010-05-07T09:02:30.000Z:

Oh, I forgot to say that I'm using TinySort 1.04

execute.it said, at 2010-06-22T14:02:27.000Z:

I can not confirm the problem.

jQuery 1.4.2
UI 1.8.2
tinysort 1.0.4
FF 3.6

I hope it also works in all other major browsers.

AndresRamirez108 said, at 2010-12-26T05:40:14.000Z:

Update to 1.0.4 fixed that problem for me. I had this issue for a long time and was about to post how I have the same error for any version of jQuery after 1.3.2, but I updated tinysort (right before I posted, from 1.0.2 to .4) and it works!

jQuery 1.4.4
UI 1.8.7
tinysort 1.0.4
FF 3.6.10

Thank you for such nice job with this plugin ;)

Tinysort with IE9

Hi,

i think there is a problem using Tinysort 1.0.4 under IE9.
It seems that the plugin just not working with IE9.
Can you check please?

What version of the product are you using?
Tinysort 1.0.4
jQuery 1.5.2
IE 9

Migrated from http://code.google.com/p/tinysort/issues/detail?id=11


earlier comments

sjeiti said, at 2011-06-17T21:35:34.000Z:

Nope, everythings fine in my IE9.0.8112.16421

sjeiti said, at 2011-08-02T11:36:32.000Z:

...even passes the unit tests I wrote, so I'm closing the issue.

Patch for using .val() instead of .text()

By adding useVal setting, input elements can be sorted based on their value.

Thanks for the plugin.

Migrated from http://code.google.com/p/tinysort/issues/detail?id=4


earlier comments

sjeiti said, at 2011-06-17T22:09:41.000Z:

Cool idea thanks... will update somewhere soon. ps: sorry for the lack of updates, issues weren't going to my inbox

sjeiti said, at 2011-06-18T13:34:07.000Z:

I've also added an example for useVal: http://tinysort.sjeiti.com/#xinp

Table sorting example code

I could not get this line in your example:

$('#xtable>tbody>tr').tsort('td:eq('+nr+')[abbr]',{order:aAsc[nr]});

to work in my application, but this worked fine:

$('#xtable>tbody>tr').tsort('td:eq('+nr+')',{attr:'abbr',order:aAsc[nr]});

All the other lines are identical to your example. jQuery level is 1.7.2

Russ

Migrated from http://code.google.com/p/tinysort/issues/detail?id=31

Random start location?

This isn't really an "issue," so I apologize in advance.

I would like to have the script pick a random point in a list as the starting point, while maintaining the same order. Any ideas how to achieve this?

Migrated from http://code.google.com/p/tinysort/issues/detail?id=5


earlier comments

renee.shadforth said, at 2010-07-15T21:59:17.000Z:

Thank you for the great script, by the way.

sjeiti said, at 2011-06-17T20:49:23.000Z:

ps: http://api.jquery.com/gt-selector/

Licensing of JavaScript files

Looking in trunk, the licensing of two of the .js files isn't clear/defined.

jquery.tinysort.min.js - this doesn't have a license header. Not a huge deal, but your license says that it should be there.

More importantly, the following file is hard to determine the license for as it doesn't seem to exist elsewhere:

jquery.opensource.min.js - no license header and not obvious what the license is.

It's also a bit confusing name-wise, implying that there's an 'open source' plugin for jquery somewhere. It seems to be your code, so presumably is a personal util file of some kind(?).

Sorry to be pedantic around the licensing :)

Migrated from http://code.google.com/p/tinysort/issues/detail?id=34


earlier comments

sjeiti said, at 2012-08-18T20:51:54.000Z:

I'll have a thorough look at this in a few days. I'm in the midst of switching the lot over to Github. Still have to check how licensing is done over there.

The jquery.opensource.min.js is indeed some code I use for my opensource projects. It's not a plugin, I just prepend the filename to indicate jQuery dependency. It's only use is for the index.html file, it doesn't need a license.

sorting uses table cells to determine sort-type, not abbr values

> What steps will reproduce the problem?

  1. Make a table column with integers for the abbr value and $ values in the cell <td>s
  2. Use multiple digit numbers (not all 4-digit numbers).
  3. When you sort, it will sort alphabetically, even though the abbr values are all numerical.

> What is the expected output? What do you see instead?

I would expect that the abbr value would be used to detect alpha vs. numeric sorting!

> What version of the product are you using?

jQuery 1.4.3 (same behavior on 1.4.1)
tinysort 1.0.4

> Other info

I've been using tablesorter, but I find it bloated and inelegant compared to your code. It is also completely ineffectual with this exact issue of displaying one value and sorting on another. I really hope you have a solution!

I've attached an example that demonstrates the problem ... index2.html can be place right in the project download folder.

Cheers,
Neokio

Migrated from http://code.google.com/p/tinysort/issues/detail?id=7


earlier comments

sjeiti said, at 2011-06-17T21:24:30.000Z:

You have to explicitly tell to sort on the attribute. See your example in working order here: http://jsfiddle.net/Sjeiti/bFAJ9/9/

Possible issue with iterating over object keys

See line 232 and 235. Is there any reason that these are for/in loops, even though they seem to be iterating over an array? This causes an exception on a site I'm working on because it eventually loops over a method of the array, which, being a function, doesn't have the 's' property. I'm not really following the rest of the plugin code, so I'm not sure if I'm missing something.

Screen Shot 2013-03-26 at 4 42 19 PM

I dropped in the following code, and it seems to work fine now:

//
// sort
$.each(aElements, function() { this.s.sort(fnSort); })
//
// order elements and fill new order
$.each(aElements, function() {
  var oParent = this

Can not make returns work!

I have two DIV as such

Brickell Key Williams Island Bimini, Bahamas Brickell Doral Downtown Midtown Sunny Isles Beach

I need to have in the second "empty" DIV (projectsFlow), the "img" with attribute rel="P" sorted by attribute "alt" from the first DIV (projectsFlowO)

This is the code that I was using

$('#projectsFlow').html($('div#projectsFlowO>img[rel="P"]').tsort({returns:true},{order:'asc', attr:'alt'}));

but the sorting does not work!

Since I could not make it work with the previous line I have to settle for the following lines which do work!

$('div#projectsFlowO>img[rel="P"]').clone().appendTo('#projectsFlow');
$('div#projectsFlow>img').tsort({order:'asc',attr:'alt'});

Any suggestions will be appreciated

Thanks in Advance

Sorting Criteria

Hi,

What is the sorting criteria if the criteria value is the same on all the elements.

I have this example: http://jsfiddle.net/6GBuT/4/

If I sort by score, the first 3 items will have the score 4. By what criteria is the first 3 results sorted?

Can I set a sub criteria to be the 'order value' so that the first 3 results will be sorted by that?

Thank you,
Adrian

Filtering?

Is it possible to Filter items rather than just sort them? EG. - Only show items that match.

tsort() sorts differently to the normal sort()

I have the following:

<ul id="venues">
<li>The Perfect Pita</li>
<li>TNR Cafe</li>
<li>Uptown Cafe</li>
<ul>

and I have
venues = ['The Perfect Pita', 'TNR Cafe', 'Uptown Cafe'];

venues.sort(); // Produces the list ['TNR Cafe', 'The Perfect Pita', 'Uptown Cafe'] order,

However, $('#venues ul>li').tsort() produces the list ['The Perfect Pita', 'TNR Cafe', 'Uptown Cafe']

Notice how the first two elements are the other way around. This led to a minor bug on my site as I made the assumption that sort() and tsort() would order items in the same way.

I tracked the difference down to the zeSort function which toLowerCase() the strings. If I remove that then the sort seems somewhat consistent now.

Is there any way you can use the default sort() function?

Otherwise awesome jquery plugin. Thanks!

Migrated from http://code.google.com/p/tinysort/issues/detail?id=13


earlier comments

sjeiti said, at 2011-07-27T08:29:48.000Z:

I'm not going to use the default sort function; technically I can't, and more importantly: making a disctinction between upper- and lowercase for and alphabetical sort is a bit stupid.

I will make the toLowerCase optional, but keep it turned on by default (which can easily be set globally).

[email protected] said, at 2011-07-27T12:48:12.000Z:

Hi, well perhaps instead of making lowercase optional, how about you allow me to pass in a custom sort function. Then I have complete control, lowercase or not, numberic sort or not, etc.

thanks
Andrew

sjeiti said, at 2011-08-02T11:44:44.000Z:

...looking at it right now... maybe I should do both...

Sorting with swedish letters

Sorting with swedish letters (and norwegian, danish etc.) does not work properly. The sorting order should be:

ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ

but the applied sorting order is:

AÄÅBCDEFGHIJKLMNOÖPQRSTUVWXYZ

this is a problem in javascript as well so it needs some custom coding..

Migrated from http://code.google.com/p/tinysort/issues/detail?id=8


earlier comments

[email protected] said, at 2011-03-15T10:52:42.000Z:

The same with Polish Letters :( Any idea?

sjeiti said, at 2011-08-02T12:44:09.000Z:

Ah... found that this is essentially similar to issue 14. Consider it fixed for the next version.

sjeiti said, at 2011-08-02T13:06:33.000Z:

set the 'cases' property to true to fix

"t.s is undefined" and "s.s is undefined"

I'm getting somewhat random errors when sorting a list of photos. The errors are "t.s is undefined" and "s.s is undefined". Both are jquery.tinysort.min.js Line: 1. Code is below. All HTML is inside of jQuery Tools tab container and jQuery version is 1.4. If you need to view my live page, please contact me via email.

Sample HTML:
<select id="photosort">
<option selected="" value="sort">Preferred Order</option>
<option value="title">Title</option>
<option value="added">Most Recent</option>
<option value="comments">Most Comments</option>
<option value="favs">Most Favorited</option>
</select>

<ul class="itemlist columns5" id="photolist">
<li sort="0000000000" added="1254952753" title="title 1" favs="0000000001" comments="0000000003">photo</li>
<li sort="0000000001" added="1266912490" title="title 2" favs="0000000003" comments="0000000013">photo</li>
<li sort="0000000002" added="1267102128" title="title 3" favs="0000000008" comments="0000000014">photo</li>
</ul>

Sample jQuery:
$("#photosort, #photosortdir").change(function(){
var sdir = "asc";
if ($("#photosort").val() == 'comments' || $("#photosort").val() == 'favs' || $("#photosort").val() == 'added') {
sdir = 'desc';
}
$("UL#photolist &gt; LI").tsort(attr:$("#photosort").val(),order:sdir});
return false;
});

Migrated from http://code.google.com/p/tinysort/issues/detail?id=6


earlier comments

szsori said, at 2010-07-29T15:00:29.000Z:

Note that our tsort line is actually: $("UL#photolist &gt; LI").tsort({ attr: $("#photosort").val(), order: sdir });

For some reason the { got dropped in my first post.

sjeiti said, at 2011-06-17T20:59:34.000Z:

I'm not getting any errors: http://jsfiddle.net/Sjeiti/aVA2x/4/ Any specific browser?

ps: sorry for the extremely late reply

Numbers in attr do not sort properly

I have a list that is 140 items long (and growing), and I was able to get the alphabetical sorting working correctly, but when I try to do sorting numerically it doesn't work. I have a number in a class (have tried it in rel="1" and data-order="1"). It seems the attr: class isn't reading the number

Here is my fiddle so you can see what is going on.
http://jsfiddle.net/pSNG9/1/
I have shortened the list for readability.

Am I missing something here or does the attr only read strings?

use of isNum produces unexpected results

This is a fix I applied for my situation and I thought I'd mention it in case you think someone else might need it.

I have a set of data that includes numbers and text and I always want it to sort everything as text. By default it's mixing the styles because the isNum function is only called when comparing two items.

To enable the ability to turn off the parseFloat() conversion I added an option "parseNums: true" and then wrapped an "if" around the code that checks if it should convert to float:

            if (oSettings.parseNums) {
                if (isNum(a.s) &amp;&amp; isNum(b.s)) {
                    x = parseFloat(a.s);
                    y = parseFloat(b.s);
                }
            }

and then just call it with that option turned off:

$("#MyDropdown").tsort({ parseNums: false });

Migrated from http://code.google.com/p/tinysort/issues/detail?id=15


earlier comments

sjeiti said, at 2011-08-02T19:36:50.000Z:

Issue 16 has been merged into this issue.

sjeiti said, at 2011-10-12T22:26:58.000Z:

Introduced a new parameter 'forceStrings' (defaulting to true) in version 1.1.1 (now in the repository). In essence similar to your 'parseNums' but better in naming because forceStrings=true will always result in strings, whereas parseNums=true will mostly result in numbers but sometimes in strings. Will make 1.1.1 download as soon as I've added a regression test for this issue.

Custom sortFunction

Can you please provide more documentation/example how to use
tinysort with custom sortFunction.

Migrated from http://code.google.com/p/tinysort/issues/detail?id=18


earlier comments

sjeiti said, at 2011-10-12T22:16:55.000Z:

Ah yeah sorry about that: the custom sort wasn't really intuitive. I've added better documentation with version 1.1.1 to the repository (haven't created a new download yet)

sorting numbers fails when surrounded by whitespace

Numbers are not recognized as numbers, when there are leading and trailing whitespace characters.

I had to add following lines to the code to strip them:

sA=sA.replace(/^\s_/i,'').replace(/\s_$/i,'');
sB=sB.replace(/^\s_/i,'').replace(/\s_$/i,'');

With this, numbers are correctly interpreted and sorted as numbers.

sort problem with greek characters

hi there!

nice work with your plugin but doesn`t work well with greek characters.

it doesn`t sort all of the words correctly

you can see an example here http://jsfiddle.net/zGpWQ/6/

no matter what browser or jquery version, it makes the same mistakes.

any ideas?

Migrated from http://code.google.com/p/tinysort/issues/detail?id=22


earlier comments

sjeiti said, at 2012-02-08T16:24:58.000Z:

Hi... Yeah this is not really a TinySort bug. This is just how Javascript sorts Greek strings. See adjusted JSFiddle here: http://jsfiddle.net/Sjeiti/LTDWA/

A possible workaround could be parsing a custom sort function...
But I'll go see if I can come up with a solution since this problem occurs for other languages as well.

sjeiti said, at 2012-02-08T23:57:07.000Z:

How's this? http://jsfiddle.net/Sjeiti/LTDWA/3/

If this custom sort function is correct I will go and build it into TinySort.

papadopoulos.takis said, at 2012-02-09T00:14:22.000Z:

Unfortunately my friend this doesn`t work properly, neither did the previous one with the array.

If we could make a letter order map like
(α,ά,β,γ,δ,ε,έ,ζ,η,ή,θ,ι,ί,ϊ,ΐ,κ,λ,μ,ν,ξ,ο,ό,π,ρ,σ,τ,υ,ύ,φ,χ,ψ,ω,ώ)
i think it would work.

You see for example "δανείζω" should be before "δέχομαι" because it`s like "danizw, dechomai", a before e. BUT if it was δαν... and δεχ (ε=έ |'helps in reading) it works fine. try http://jsfiddle.net/LTDWA/4/

larsmjo said, at 2012-02-15T11:03:14.000Z:

Hi,

I have same problem with Danish chars:
http://jsfiddle.net/lmojo/wJq86/

sjeiti said, at 2012-02-15T12:09:38.000Z:

ok... getting there... http://jsfiddle.net/Sjeiti/Pnm8T/ It will become slightly slower because of an extra for-loop.

As you can see, Greek now uses the data-order attribute with the list Takis provided. This orders somewhat correctly but does not yet account form -normal- characters and numbers. I think I'll finally implement this as an extra default value you can set: as in $.tinysort.defaults.lang or whatever....

Have to get back to real work now... :-)

sjeiti said, at 2012-02-17T13:02:06.000Z:

I think I have fixed it: http://jsfiddle.net/Sjeiti/Jyx59/ Please verify and I will commit the source.

If you check the source on Jsfiddle you'll see I set the order like this:
$.tinysort.defaults.charOrder = 'zæøå';
But you could of course also do:
$.tsort({charOrder:'zæøå'});

It works as follows:
The charOrder string is checked for non-latin chars. Each time it encounters non-latin chars in a row it will append it to the previous latin char (or 'z' if charOrder contains only non-latin chars).
So charOrder or 'abczæøå' or 'zæøå' or 'æøå' will all result in 'abcdefghijklmnopqrstuvwxyzæøå'.
A charOrder of 'aåbøczæ' will result in 'aåbøcdefghijklmnopqrstuvwxyzæ'.
etcetera...

The only thing I have not yet fixed are sorting foreign characters that consist of more characters, ie: 'lj' in Servo-Croatian, 'ch' in Spanish or 'ss' in German.

papadopoulos.takis said, at 2012-02-17T15:06:34.000Z:

hi there!

it`s a lot better than before but not quite perfect yet for greek.
see here http://jsfiddle.net/Jyx59/80/

-it may be my mistake. sorry for that!-

I only gave you the lowercase order for the greek characters the last time.
This is the correct order for lower and upper case letters:

α,ά,β,γ,δ,ε,έ,ζ,η,ή,θ,ι,ί,ϊ,ΐ,κ,λ,μ,ν,ξ,ο,ό,π,ρ,σ,τ,υ,ύ,ϋ,ΰ,φ,χ,ψ,ω,ώ
A,Ά,Β,Γ,Δ,Ε,Έ,Ζ,Η,Ή,Θ,Ι,Ί,Ϊ,Κ,Λ,Μ,Ν,Ξ,Ο,Ό,Π,Ρ,Σ,Τ,Υ,Ύ,Ϋ,Φ,Χ,Ψ,Ω,Ώ

where each line should be considered the same while sorting:
http://en.wikipedia.org/wiki/Greek_diacritics#Unicode

α,ά,A,Ά
β,Β
γ,Γ
δ,Δ
ε,έ,Ε,Έ
ζ,Ζ
η,ή,Η,Ή
θ,Θ
ι,ί,ϊ,ΐ,Ι,Ί,Ϊ
κ,Κ
λ,Λ
μ,Μ
ν,Ν
ξ,Ξ
ο,ό,Ο,Ό
π,Π
ρ,Π
σ,Σ
τ,Τ
υ,ύ,ϋ,ΰ,Υ,Ύ,Ϋ
φ,Φ
χ,Χ
ψ,Ψ
ω,ώ,Ω,Ώ

larsmjo said, at 2012-02-20T09:24:53.000Z:

Really like the .charOrder solution Nice

For Danish the only thing missing is the double charachter Aa = Å
It's primary used for city names

http://jsfiddle.net/lmojo/wJq86/
Anders, København, Æble, Øresund, Åben, Aarhus, Åse

or

The correct sort order for the following cities are:
Aabybro,Åbyhøj,Aakirkeby,Aalborg,Aalborg,Aalborg,Aalborg SV,Aalborg SØ,Aalborg Øst
Ålbæk,Aalestrup,Ålsgårde,Aarhus C,Aarhus C,Aarhus N,Aarhus V,Årre,Aars,Årslev,Aarup

(MS SQL Collation: SQL_Danish_Pref_CP1_CI_AS + Danish MS Excel) will sort like that.

This is a minor thing - I could live with Aa comming before abc...

sjeiti said, at 2012-02-24T14:48:17.000Z:

Ok... I've committed version 1.3.19 Watch it here... http://jsfiddle.net/Sjeiti/Jyx59/

For characters consisting of multiple characters, or for characters that need to be ordered similar to another you can use curly braces:

ι{ί=ι} ί sorted similar to ι
d{dž} dž sorted after d
å{Aa=å} Aa sorted similar to å

One slight bug still persists and that is the sorting of lowercase vs uppercase. I originally ignored cases. In Unicode [A-B] comes before [a-b] (plus there are some characters in between) while normally lowercase should go before uppercase. But that's another issue... :-)

papadopoulos.takis said, at 2012-02-24T17:06:04.000Z:

nice job, once again!

sjeiti said, at 2012-02-27T11:31:24.000Z:

Since characters sorted similarly is quite common I've made one slight change in orderChars notation.

So instead of: α{ά=α}βγδε{έ=ε}ζη{ή=η}θι{ί=ι}{ϊ=ι}{ΐ=ι}κλμνξο{ό=ο}πρστυ{ύ=υ}{ϋ=υ}{ΰ=υ}φχψω{ώ=ω}
you now write: α[ά]βγδε[έ]ζη[ή]θι[ίϊΐ]κλμνξο[ό]πρστυ[ύϋΰ]φχψω[ώ]

You can mix this with the curly braces, so the former Danish å{Aa=å} is now å[{Aa}]

I'm updating the documentation now... will commit in an hour or so...

larsmjo said, at 2012-03-05T07:23:03.000Z:

Just tested this - it works perfectly Like the charOrder parametre solution - brilliant !

Re-sorting with order options, dont work

I would sort a jquery-ui selectable list, with the selected elements before the unselecteds.
I used:
$('ol#sost3a>li').tsort({order:'desc',attr:'class'});
fine.
If I call a second time the same script, it resverse the elements, but I think it must maintain the order setted as descendant.
Best regards

Sort by multiple properties

Allow sorting by multiple properties.
For example: first sort items by a number property of the item and then by a name property.

Item1 : abc, 15
Item2 : bcd, 18
Item3 : cde, 14
Item4 : bcd, 14

Sort by name: Item1 > Item2 > Item4 > Item3
Sort by number: Item3 > Item4 > Item1 > Item2
Sort by name THEN number: Item1 > Item4 > Item2 > Item3
Sort by number THEN name: Item4 > Item3 > Item1 > Item2

Migrated from http://code.google.com/p/tinysort/issues/detail?id=19


earlier comments

sjeiti said, at 2012-01-30T11:30:59.000Z:

I don't suppose you have an idea on how to solve this? I've known this mixed literal/numeral issue since day one and have never come up with an elegant solution, and I'm not going to implement a slow and bloated solution.

The difficulty here is that a normal sort does not know the other values in advance.

Your items all have nice looking values but consider something like:
[a1,a,a0,aa2,b,b12,b1a2,a01c,b3a2v2].
You'd have run through the list once before sorting, then decide that the minimal sort matching /d is 4 loops since it's the lowest common denominator for the values 'b1a2' and 'b3a2v2'.

But that's just off the top of my head. I'm sure other people have come up with a better approach.

...any thoughts?

ashleymg said, at 2012-02-04T16:51:08.000Z:

Maybe I'm not following your thoughts correctly, but I'm going to assume that the use-case would have two different attributes/values/place for each sorting method:

Wouldn't it be a not-so-simple sort on data-rank (which shouldn't re-order them at all), and then place them in this order: Alan, Greg, Stanley?

I don't think it's plausible (or even useful) to have tinysort sort by multiple methods on the same value.

Or, am I not following,

sjeiti said, at 2012-02-04T22:40:48.000Z:

No the problem is mixed numeral/literal.

Normally calling a sort on ['foobar11','foobar1','foobar7']
will result in ['foobar1','foobar11','foobar7']
because it handles the numbers as text (literal).

But (sometimes) we really want the result to be ['foobar1','foobar7','foobar11'].

...but maybe I've been going at it from the wrong angle (been deprived of sleep a bit lately)
I think I can sort this one out.

sjeiti said, at 2012-02-04T22:48:48.000Z:

ps... indeed the original issue Marc coined is indeed one of multiple attributes... but it's not something I'll fix the way he wants it. Since you can indeed easily do something like adding an extra data attribute.

sjeiti said, at 2012-02-05T01:00:31.000Z:

however mixed literal/numeral values are now working correctly for v1.2 (already in svn)

Example issue

What steps will reproduce the problem?

  1. click sort
  2. click sort

What is the expected output? What do you see instead?

What version of the product are you using? On what operating system?

Please provide any additional information below.

Migrated from http://code.google.com/p/tinysort/issues/detail?id=9


earlier comments

sjeiti said, at 2011-06-17T21:31:15.000Z:

It might not look nice, but it does exactly as expected.

IE - console is undefined errors

Any workaround for "console is undefined" error in IE?

Migrated from http://code.google.com/p/tinysort/issues/detail?id=21


earlier comments

sjeiti said, at 2012-02-06T15:06:15.000Z:

I thought I removed all those... I'll go check again

jasondaydesign said, at 2012-02-06T15:29:25.000Z:

thanks!

jasondaydesign said, at 2012-02-06T18:07:58.000Z:

on an aside - what is the minimum jQuery version? (I'm running 1.4.2 and it is working - but I'm not using all of the features - just a simple sort)

sjeiti said, at 2012-02-06T19:01:21.000Z:

If I remember correctly the first version was around 1.3.6 but it has so little dependencies it'll probably work in earlier versions (it only uses extend, filter, each and pushStack).

Error when sorting numbers

I'm trying to sort some divs by its attribute data-price. This attribute store a number, below follow my div elements:

<div class="box-cambio hotel" data-price="407">...</div>
<div class="box-cambio hotel" data-price="232">...</div>
<div class="box-cambio hotel" data-price="232">...</div>
<div class="box-cambio hotel" data-price="310">...</div>
<div class="box-cambio hotel" data-price="1052">...</div>
<div class="box-cambio hotel" data-price="264">...</div>
<div class="box-cambio hotel" data-price="243">...</div>
<div class="box-cambio hotel" data-price="279">...</div>
<div class="box-cambio hotel" data-price="256">...</div>
<div class="box-cambio hotel" data-price="198">...</div>
<div class="box-cambio hotel" data-price="216">...</div>

Then I try to order it, but it does not sorts in the correct order. I'm using the following code:

jQuery(document).ready(function(jQuery) {
$('.hotel:not(.first_hotel)').tsort({attr:'data-preco'});
});

Though if i use the same code above in the Firebug's console (or Google Chrome's) it works perfectly.

Migrated from http://code.google.com/p/tinysort/issues/detail?id=33


earlier comments

sjeiti said, at 2012-08-13T18:45:29.000Z:

Are you sure it's not the typo you made? Because it worksfine here: http://jsfiddle.net/Sjeiti/V5HUr/ ... you can also use data instead of attr:'data-...

sjeiti said, at 2012-08-13T20:01:48.000Z:

I'm sorry... I don't see the issue.. . I've checked the page and it does sort at the start... but since you just execute .tsort() without parameters it will sort by text contents.

I've also checked the use of .tsort({data:'preco'}) in the console and this also seems to work.

I'll close this issue for now, unless you can reproduce/isolate it in a JSFiddle...

italoaaoliveira said, at 2012-08-13T20:17:09.000Z:

Sorry for bringing this to the wrong place, so. You can close it.

But as I'm already here, let me ask: which parameters should I use to make the plugin sort by numbers instead of shorting by text? I took a look at the examples page before posting this issue and didn't get what I have to do to obtan this result.

italoaaoliveira said, at 2012-08-14T13:46:46.000Z:

Oh, I see now how to do it parsing a custom sort function. I think that an option to sort considering numbers would be a very useful feature.

sjeiti said, at 2012-08-14T14:30:32.000Z:

Didn't you see the fiddle? Sorting numbers should work fine by default. (unless it's really a crossbrowser bug)

italoaaoliveira said, at 2012-08-17T12:20:01.000Z:

Yeah, it works perfectly in the JSFiddle, as it does when I hit the firebug console. But inside the page code, the same code does not work. As you said, it sort it as a text. I'm gonna keep trying to figure out what is happening in the page or just stick with some custom sort function.

I've read a question in Stackoverflow of someone with the same problem: http://stackoverflow.com/questions/9508146/jquery-tinysort-not-sorting-numbers-correctly. I think that a parameter to specify sorting to consider only numbers would be great.

Anyway, thanks for the help and congratulations for the amazing plugin.

italoaaoliveira said, at 2012-08-17T12:49:39.000Z:

It works well using a custom sort function. I deleted the comment with that link for the page, the company asked me that.

Sorry if I came here with a not real issue, but that sugetion to consider only numbers still on. It could be a value of the parameter 'order', maybe?

Well, thank you for your attention and for building this plugin.

sjeiti said, at 2012-08-17T13:37:32.000Z:

I'll look into it as soon as I've ported TinySort to Github

italoaaoliveira said, at 2012-08-17T13:38:57.000Z:

That's great! Thank you.

sjeiti said, at 2012-08-17T13:41:38.000Z:

:-) No problem, just don't hold your breath for it. I fear this Github port might take a while.

italoaaoliveira said, at 2012-08-17T16:23:55.000Z:

Haha, I see. Good luck with that!

Sorting Dates

Sorting dates does not give expected results when using yyyy-mm-dd or mm-dd-yyyy.

http://jsfiddle.net/BaJXe/1/

I think the issue has to do with the mixed literal/numeral feature such that it is treating the last part as a negative number -dd or -yyyy.

Setting "forceStrings" to true corrects it, but this appears to be an undocumented setting so it took me a while to figure out what was going on.

Thanks for your work!!

use of isNum produces unexpected results

This is a fix I applied for my situation and I thought I'd mention it in case you think someone else might need it.

I have a set of data that includes numbers and text and I always want it to sort everything as text. By default it's mixing the styles because the isNum function is only called when comparing two items.

To enable the ability to turn off the parseFloat() conversion I added an option "parseNums: true" and then wrapped an "if" around the code that checks if it should convert to float:

            if (oSettings.parseNums) {
                if (isNum(a.s) &amp;&amp; isNum(b.s)) {
                    x = parseFloat(a.s);
                    y = parseFloat(b.s);
                }
            }

and then just call it with that option turned off:

$("#MyDropdown").tsort({ parseNums: false });

Migrated from http://code.google.com/p/tinysort/issues/detail?id=16


earlier comments

michael.thornberry said, at 2011-08-02T15:38:20.000Z:

Sorry for the double-post, I accidentally double-clicked the submit button (I blame the carpal tunnel syndrom)

Javascript error because of syntax not working for lower IE version

Please provide a 'working' example (eg on http://jsfiddle.net/).

What steps will reproduce the problem?

  • Use IE9 and press F12 to open debugger window
  • Use Browser Mode: IE8, document mode: IE8 standards
  • click Scripts -> start debugging
  • it will stop at error:
    SCRIPT438: Object doesn't support property or method 'indexOf'
    // create basic latin string chars 32-255
    for (var i=32,s=frCrCd(i),len=255;i<len;i++,s=frCrCd(i).toLowerCase()) { // using lowerCase instead of upperCase so _ will sort before
    if (aAllChars.indexOf(s)!==-1) aAllChars.push(s);
    }
    aAllChars.sort();

What is the expected output? What do you see instead?
No Error

What version of TinySort with what version of jQuery on what OS and
browser?

tinysort 1.3.25
IE9 using

Please provide any additional information below.

Migrated from http://code.google.com/p/tinysort/issues/detail?id=30


earlier comments

michaelbracks2001 said, at 2012-06-10T07:12:42.000Z:

The solution: http://stackoverflow.com/questions/1744310/how-to-fix-array-indexof-in-javascript-for-ie-browsers

michaelbracks2001 said, at 2012-06-10T07:14:42.000Z:

Or: http://api.jquery.com/jQuery.inArray/

michaelbracks2001 said, at 2012-06-10T07:28:04.000Z:

The fix:

if (jQuery.inArray(s, aAllChars)!==-1) aAllChars.push(s);

Percentages not intelligently sorted

Given a list of elements containing percentages, for example,
<div class="score">50%</div>
<div class="score">99%</div>
<div class="score">25%</div>
<div class="score">1%</div>
<div class="score">100%</div>
<div class="score">75%</div>

The expected output of $(".score").tsort({order:"desc"});​ would be:

100%
99%
75%
50%
25%
1%

Unfortunately, this is the mixed-up result instead:

99%
75%
50%
25%
100%
1%

JSFiddle: http://jsfiddle.net/ADALj/

It would be nice to have a friendly way of controlling the sorting method applied. In the documentation on "mixed literal and numeral" it says "In a normal sort the order would be a1,a11,a2 while you'd really want it to be a1,a2,a11. TinySort corrects this." But in this specific case, we do want the normal sort order.

Migrated from http://code.google.com/p/tinysort/issues/detail?id=29


earlier comments

sjeiti said, at 2012-04-14T20:31:36.000Z:

That 'mixed up' result is indeed the normal literal way of ordering because as a literal '%' has precedence over any number. The crux is how far to go with 'intelligent' sorting before ending up with a not-so-tiny sorting plugin filled with features one would rarely use.

Most of these issues can easily be dealt with anyway. In your case: you could use some CSS3 or the data attribute (or even value if you use a list): http://jsfiddle.net/Sjeiti/AWZVx/

So unless you have a generic solution I going to have to throw this onto the wontfix pile. And by generic I mean something that could also work with date, time, potatoes and currency (maybe the only solution is parsing your own regular expression).

martinburch said, at 2012-04-14T22:45:29.000Z:

Yes, after submitting this bug I decided I would have to bite the bullet and put in the percentage value as data as well as text, and TinySort handles that well. Thanks for suggesting the CSS3 approach as well.

Since TinySort includes support for custom sorting functions, I think that's about as much as can be done to provide a generic solution. I see your point -- there are various sorts (currency, dates, etc.) that could easily turn TinySort into HugeBloatedSort.

Sorting with "non-latin" characters

When sorting text with accented characters there seems to be a subtle issue with using square brackets for character equivalence, eg the French charOrder as provided on the Tiny Sort home page: 'a[àâ]c[ç]e[éèêë]i[ïî]o[ôœ]u[ûù]'

Here is a sample of the issue, http://jsfiddle.net/johnmcalvert/dLrzN/.

The correct sort order ascending should be:

égypte
émirats arabes unis
équateur
érythrée
espagne
estonie
états-unis
éthiopie

since all the variants of "e" are declared equal in the charOrder expression.

Orderby x - then by y

Hi,

Does Tinysort support orderby x, y ?

I can do this by tsort twice:
http://jsfiddle.net/lmojo/rLaHT/
But performance goes down...

Found this:
http://stackoverflow.com/questions/3116172/jquery-sorting-of-div-elements-based-on-count-and-date-time-timestamp

Migrated from http://code.google.com/p/tinysort/issues/detail?id=23


earlier comments

sjeiti said, at 2012-02-15T14:07:28.000Z:

No it doesn't support the x,y sort but that stackoverflow link doesn't seem that hard to implement... I will give it a shot when I have time...

larsmjo said, at 2012-02-20T13:13:56.000Z:

Dont't work sorting twice :-( http://jsfiddle.net/lmojo/rLaHT/12 (see data-sp="4")

Really looking forward to this one

sjeiti said, at 2012-02-20T13:24:47.000Z:

No that doesn't, here's temporary workaround that does work: http://jsfiddle.net/Sjeiti/rLaHT/17/

larsmjo said, at 2012-02-20T15:27:40.000Z:

Problem is that lenght of 'id' should be the same on all elements. Same for 'data-sp'. http://jsfiddle.net/lmojo/rLaHT/20/

If I change the lenght on 'id' it don't work: http://jsfiddle.net/lmojo/rLaHT/21/
I need the 'id' for identifying unique elements for later dom update...

sjeiti said, at 2012-02-20T15:55:23.000Z:

Well that's because it will 'see' it as a numeral value.

You could change it to this: http://jsfiddle.net/Sjeiti/rLaHT/31/

This could even work for multiple values if the values stay within a range: in this example the id cannot go higher than 999 since that would cause it to be '1' in the temporary data-foo. For a higher range you'd have to divide the 'id' by a higher number.

So more values can be added by dividing or multiplying by something twice as high, ie: 33*1E4 + 33 + 33/1E3 + 33/1E6 = 330033.033033 (where each of the 33's would be a different value).

Needless to say this would only work with numerals.

larsmjo said, at 2012-03-05T13:21:06.000Z:

One of my collums is non numerals :-( http://jsfiddle.net/lmojo/rLaHT/34/

id is a SQL nvarchar(15)
data-sp is a SQL tinyint

Would like to be able to sort like this:
Sortby data-sp, id (both asc or both desc)

sjeiti said, at 2012-03-05T16:48:37.000Z:

...well I'm working on implementing a solution, but it proves a bit more difficult than I anticipated.

Doesn't Accept Objects

I may be mistaken - and let me know if I am - but tsort() doesn't seem to accept objects, so I can't compile args programmatically in the event that I am sorting on multiple columns.

var obj = {};
obj{ 'span.surname' } = {
    order: 'asc'
};

$('ul#people>li').tsort( obj );

My question is just why can't I pass an object like this to tsort?

Non-sorted elements are sorted to the top, regardless of "place" setting

I ran into this problem in my own project and then realized that the "sorting tables" example behaves the same way. The example states that with the default "place" setting, non-sorted elements should always be at the bottom of the list, but it doesn't work that way in the example. In my own project, no matter what "place" setting I use, non-sorted items are always at the top of the list.

Github

can you switch to github?

Migrated from http://code.google.com/p/tinysort/issues/detail?id=28


earlier comments

sjeiti said, at 2012-04-13T10:04:52.000Z:

I might... but not in the near future since I'm not yet as comfortable with Github as I am with SVN.

sjeiti said, at 2012-07-03T08:36:45.000Z:

...thinking about it some more. Check here: https://docs.google.com/spreadsheet/viewform?formkey=dEZHY0hFTXJ6Q1ZFUzZVcVpmM0t4V3c6MQ

[email protected] said, at 2012-07-03T08:53:31.000Z:

where can i see the result or current status? :-)

sjeiti said, at 2012-07-03T21:13:35.000Z:

I'll post the results on sjeiti.com in a while. But you needn't worry: Github is winning by a landslide. (you're not spamming the form are you?... ;-P )

italoaaoliveira said, at 2012-08-17T12:52:40.000Z:

Github is great! This plugin would be my very first fork there. ;)

sjeiti said, at 2012-08-17T13:01:36.000Z:

Yeah it is... and the final conclusion is that I will migrate to Github (I think the overal result was about 30 to 1 :-)

The only problem now is that I would like to migrate the entire SVN history to Github as well. I think I read somewhere on Github that this is possible, but also a bit of a pain in the ass.

I was a bit swamped in work but hopefully I will have some time in the next two weeks.

Not working in IE 9

Your plugin is working great for me on Chrome and Safari. However, it is not working at all in IE 9 (version 9.0.8112.16421) on Windows 7.

Nothing sorts and even the examples on your website don't even show up.

http://tinysort.sjeiti.com/test.html
Says:
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.2; .NET4.0E)

Tests completed in 21 milliseconds.
0 tests of 0 passed, 0 failed."

Thanks,
Bill

Migrated from http://code.google.com/p/tinysort/issues/detail?id=20


earlier comments

sjeiti said, at 2012-02-04T10:56:28.000Z:

damn IE and console.log

Not ordering anything with jQuery 1.4.3

Here's the html:

<select class="wpsc_select_variation" name="variation[45]" id="variation_select_9_45">
<option value="0" disabled="">-- Please Select --</option>
<option value="52">Black</option>
<option value="53">Blue</option>
<option value="51">Green</option>
<option value="55">Orange</option>
<option value="50">Red</option>
<option value="57">Tope</option>
<option value="56">Violet</option>
<option value="54">Yellow</option>
</select>

Here's my js:
$('select.wpsc_select_variation>option').tsort("",{orderby:"value"});

and I've also tried:
$('select.wpsc_select_variation>option').tsort("",{order:"asc",attr:"value"});

Neither are working for me. I also tried just the basic sort with an unordered list and it still didn't work.

Any thoughts? Thanks.

OSX 10.6
Chrome 10.0.648.204
jQuery 1.4.3

Migrated from http://code.google.com/p/tinysort/issues/detail?id=12


earlier comments

sjeiti said, at 2011-06-17T21:44:42.000Z:

It works when I test with jQuery 1.4.4 http://jsfiddle.net/Sjeiti/XJZNn/

marclipovsky said, at 2011-06-18T08:52:43.000Z:

Check it again cause it's not working in 1.4.4. Thanks!

Marc Lipovsky
[email protected]
marcandkatie.co.za

sjeiti said, at 2011-06-18T09:55:55.000Z:

Alright... this time I included 1.4.4 and it still works: http://jsfiddle.net/Sjeiti/XJZNn/

But maybe you meant to do: $('#asdf>option').tsort("",{attr:"value"});

Although I do agree there's something with 'orderby', I have no idea why it's in the documentation. Must be a remnant of an earlier version. I'll go fix the documentation.

marclipovsky said, at 2011-06-18T09:59:45.000Z:

Thanks man. Shame that it's still not working. No worries though I ended up just numbering the items i.e. 1. Red, 2. Green, etc.

Marc Lipovsky
[email protected]
marcandkatie.co.za

sjeiti said, at 2011-06-18T13:16:16.000Z:

Ehrm... in what browser is this http://jsfiddle.net/Sjeiti/XJZNn/9/ not working? I've tested in Chrome.

this.setArray is not a function

I get this error on line 109

Any help?

Thanks.

mibo

Migrated from http://code.google.com/p/tinysort/issues/detail?id=1


earlier comments

jfurey said, at 2010-03-05T01:44:57.000Z:

I also get this error.

I'm using jQuery 1.4.2.

Cheers,

James.

jfurey said, at 2010-03-05T01:52:56.000Z:

Looking through the source of TinySort 1.0.2 here:

https://gist.github.com/raw/98344/36c75765470c2cdfffc60715504a925c3efdffdf/x

...I see the line that has "this.setArray" has an alternative listed in it's comment:

// setArray or pushStack?

So in my minified version of TinySort, I change "setArray" to "pushStack" and...

YAY!

...error gone.

Cheers,

James.

sjeiti said, at 2010-03-09T22:20:26.000Z:

Fixed in 1.0.4

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.