简体   繁体   中英

Sort array on string and boolean in javascript

I am having difficulty getting this sort to work. Current always has precedence over name. I can get it to sort on the values of either current or name but not both.

My array look like this.

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

Here's the sort function.

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();
                        }
                    }
                }
            }

You're missing a return :

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

Otherwise your return value will be undefined if both current s are set:

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;
    }
}

Try

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
        }
    }

}

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM