Results 1 to 4 of 4

Thread: Javascript Array Sort method is "random" (NOT STABLE) within sort

Threaded View

  1. #1

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Javascript Array Sort method is "random" (NOT STABLE) within sort

    The Javascript array sort method (at least in Firefox) is apparently random within the sort.

    If I have an ARRAY of OBJECTS and I sort on a particular element in the object - one that has lots of duplicates - the original order is not maintained in the final sort.

    It appears random - but after a couple of clicks to sort asc and desc it does come around - so there is a pattern.

    Has anyone ever dealt with this - and come up with a real solution.

    I'm thinking of doing some kind of "sub-sort" on the original ordinal position prior to sort - but don't want to re-invent the wheel so that say...

    Code:
    function sortArray(arrSort, e, args) {
        switch (e.cssClass || "") {
            case "acs-cell-money":
                arrSort.sort(sortNumber);
                break;
            case "acs-cell-number":
                arrSort.sort(sortNumber);
                break;
            case "acs-cell-date":
                arrSort.sort(sortDate);
                break;
            default:
                arrSort.sort(comparer);
                break;
        }
        if (!args.sortAsc) {
            arrSort.reverse();
        }
        for (var i = 0; i < arrSort.length; i++) {
            //alert(i);
            arrSort[i].acsSortBits = undefined;
        }
        arrSort.lastMultiSort = "";
    }
    
    function comparer(a, b) {
        var x = (a[sortcol.field] || "").toUpperCase();
        var y = (b[sortcol.field] || "").toUpperCase();
        return (x == y ? 0 : (x > y ? 1 : -1));
    }
    Last edited by szlamany; Jan 27th, 2012 at 10:40 AM.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width