0

我很难让这种工作正常进行。当前始终优先于名称。我可以让它对当前或名称的值进行排序,但不能同时对两者进行排序。

我的数组看起来像这样。

var arr = [{current:true, name:"A name"},
           {name:"A name"}, {name:"B name"},
           {current:true, name:"B name"}];
arr.sort(sort_me)

这是排序功能。

var sort_me = function(left, right){
                var value = "name";
                var sort_by_val = function(){
                    return left[value] == right[value] ? 0 : (left[value] < right[value] ? -1 : 1);
                }
                if(left.current===right.current) {
                    sort_by_val();
                }else{
                    if(left.current===true){
                        return -1;
                    }else{
                        if(right.current===true){
                            return 1;
                        }else{
                        sort_by_val();
                        }
                    }
                }
            }
4

2 回答 2

5

你错过了一个return

if(left.current===right.current) {
    return sort_by_val();
}

undefined否则,如果两个currents 都设置了,您的返回值将是:

var sort_me = function(left, right){
    var nameorder = left.name === right.name ? 0 : (left.name < right.name ? -1 : 1);
    if(
        (left.current && right.current) || 
        (!left.current && !right.current)
    ) {
        return nameorder;
    } else if(left.current) {
        return -1;
    } else {
        return 1;
    }
}
于 2013-04-24T05:18:40.320 回答
1

尝试

var sort_me = function(left, right) {
    var value = "name";
    var sort_by_val = function() {
        return left[value] == right[value] ? 0 : (left[value] < right[value]
                                                  ? -1
                                                  : 1);
    }
    if (left.current === right.current) {
        return sort_by_val(); //missing return
    } else {
        if (left.current === true) {
            return -1;
        } else if (right.current === true) {
            return 1;
        } else {
            return    sort_by_val(); //missing return
        }
    }

}

演示:小提琴

于 2013-04-24T05:19:54.247 回答