js sort 排序方法

// 如果我们想要给任何包含简单值的数组排序,必须要做更多的工作
    var m = ['aa','bb','a',4,8,15,16,23,42];

    m.sort(function(a,b){
        if(a === b){
            return 0;
        }

        if(typeof a === typeof b){
            return a < b ? -1 : 1;
        }

        return typeof a < typeof b ? -1 : 1;
    })

    /**
     * 如果有一个更智能的比较函数,我们可以使对象数组排序。
     *
     * by函数接受一个成员名称字符串作为参数
     * 并返回一个可以用来包含该成员的对象数组进行排序的比较函数
     */

    var by = function(name){
        return function(o,p){
            var a , b;
            if(typeof o === 'object' && typeof p === 'object' && o && p){
                a = o[name];
                b = p[name];

                if(a === b){
                    return 0;
                }
                if (typeof a === typeof b){
                    return a < b ? -1 : 1;
                }
                return typeof a < typeof b ? -1 : 1;
            } else{

                throw {
                    name : 'Error',
                    message : 'Expected an object when sorting by' + name
                };

            }
        }
    }

    var s = [
        { first : 'Joe', last :'Besser'},
        { first : 'Moe', last :'Howard'},
        { first : 'Joe', last :'Derita'},
        { first : 'Shemp', last :'Howard'},
        { first : 'Larry', last :'Fine'},
        { first : 'Currly', last :'Howard'}
    ]

    // 如果你想基于多个键值进行排序,你需要再次做更多的工作

    var by =  function (name , minor){

        return  function (o,p){
            var a, b;
            if(o && p && typeof o === 'object' && typeof p ==='object'){
                a = o[name];
                b = p[name];

                if(a === b){
                    return typeof minor === 'function' ? minor(o,p) : 0;
                }

                if(typeof a === typeof b){
                    return a < b ? -1 : 1;
                }

                return typeof a < typeof b ? -1 : 1;
            } else{
                throw {
                    name : 'Error',
                    message : 'Expected an object when sorting by ' + name
                }
            }
        }
    }

    s.sort(by('last',by('first')));

猜你喜欢

转载自blog.csdn.net/qq_34579060/article/details/80902092