1

I have a JS sort script, but is ordering #'s like this:

1.
10.
11.
2.
3.
4.

I want them to be ordered by value, like this:

1.
2.
3.
4.
10.
11.

I cannot figure this out. I know there is a way to do it with MySQL, but I am unfamiliar with javascript. Here is what I have so far, but it is ordering numeric numbers incorrect. I appreciate any help you can provide, or just shooting me the right direction.

JavaScript:

var Grid = new Class({
    /** define some variables */
    table: false, 
    headers: false, 
    data: false, 

    /**
     * Initialize the object
     */
    initialize: function(table){
        this.table = table;
        this.getHeaders();
    }, 

    /**
     * Get the headers
     */
    getHeaders: function(){
        this.headers = this.table.getElements('thead tr th');
        this.headers.each(function(h, index){
            //h.store('asc', false);
            if (h.hasClass('sort')) h.addEvent('click', function(){
                if(h.hasClass('asc')){
                    h.className = 'sort desc';

                    //h.addClassName('desc');
                }else{
                    h.className = 'sort asc';
                    //h.addClassName('asc');
                }
                //if (h.retrieve('asc')) h.store('asc', false);
                //else h.store('asc', true);
                //this.sort($('tblrank_id'));
                this.sort(index);
            }.bind(this));
        }, this);
    }, 

    /**
     * Get the table data
     */
    getData: function(){
        this.data = this.table.getElements('tbody tr');
    }, 

    /**
     * Sort the data
     * @param int index
     */
    sort: function(index){
        this.getData();
        data = [];
        sortType = this.headers[index].getProperty('axis');

        asc = this.headers[index].hasClass('asc');//this.headers[index].retrieve('asc');
        if (this.data.length > 0) this.data.each(function(row, i){
            cells = row.getElements('td');
            if (cells.length < this.headers.length) return false;
            value = cells[index].innerHTML;

            if(cells[index].childNodes[0].nodeName.toLowerCase() == "a"){
                //alert(cells[index].childNodes[0].innerHTML);
                value = cells[index].childNodes[0].innerHTML;
            }

            if (sortType == 'int' || sortType == 'float'){
                if (value.contains('$') || value.contains(',')) value = value.replace(/\$/g, '').replace(/,/g, '').toFloat();
                else value = value.toFloat();
            } else if (sortType == 'date') value = Date.parse(value);
            data.push({'index': i, 'value': value, 'row': row});
        }, this);

        if (sortType == 'int' || sortType == 'float' || sortType == 'date') data.sort(this.sortNumeric);
        else data.sort(this.sortCaseInsensitive);
        if (!asc) data.reverse();

        this.data = [];
        data.each(function(d, i){
            this.data.push(d.row);
        }, this);

        this.data.each(function(row, i){
            if (row.hasClass('etblraw0')) row.removeClass('etblraw0');
            if (row.hasClass('etblraw1')) row.removeClass('etblraw1');
            this.table.getElement('tbody').adopt(row.addClass((i % 2 == 0 ? 'etblraw0' : 'etblraw1')));


        }, this);
    }, 

    /**
     * Sort Numerica Values
     * @param object a
     * @param object b
     */
    sortNumeric: function(a, b){


        if ($type(a.value) != 'number') a.value = 0;
        if ($type(b.value) != 'number') b.value = 0;
        return a.value - b.value;
    }, 

    sortCaseInsensitive: function(a, b){
        a.value = a.value.toLowerCase();


        b.value = b.value.toLowerCase();
        if (a.value == b.value) return 0;
        if (a.value < b.value) return -1;
        return 1;
    }
);
1

1 Answer 1

3

Try this:

function sortfunc(a,b) {
  return parseInt(a.split(".")[0]) -
         parseInt(b.split(".")[0]);
}

var list = ["1. first", "2. second", "10. tenth"];
list.sort(sortfunc);

console.log(list); // => ["1. first", "2. second", "10. tenth"]
5
  • tried cutting and pasting this in the bottom, by the SortNumeric code section above. Couldn't make it work. I added my full code. Thank you for the help May 1, 2012 at 0:04
  • @user1071915 the issue is that your numbers are sorting as strings. Calling parseInt is the important part of this response. @Riateche why not just use the radix, like parstInt(a, 10)?
    – fncomp
    May 1, 2012 at 0:14
  • @Josh I think it's more clear to pass only number to parseInt and cut off the rest. If I'd write parseInt(a, 10), someone can think that I've made a mistake because string a does not respesent a number. May 1, 2012 at 0:30
  • @Riateche I guess I'm just used to Python where a trailing dot is used to convert ints to floats.
    – fncomp
    May 1, 2012 at 0:34
  • 1
    @Riateche—you can get rid of the split, parseInt trims any non-numeric characters from the end of the string, the sort function can just be return parseInt(a, 10) - parseInt(b, 10);. Or you can do the split and forget parseInt since the subraction will coerce the vaulues to numbers anyway. But parseInt is likely faster.
    – RobG
    May 1, 2012 at 0:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.