0

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

2 Answers 2

5

You're missing a return:

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

Otherwise your return value will be undefined if both currents 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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.