Jordan
Jordan

Reputation: 2523

Sorting by properties by priority

I have items that I'm wanting to sort, my items have computed properties on the model that include winning, bidding, closed, and watching

each of these properties is true or false

I want to sort the items so that all the winning items are first, then all the bidding items, then all the watching items, then all the closed items.

How might I achieve this? Do I need to do it all in one sort function or can I specify multiple functions to sort by?

I've tried this for winning, but I'm not sure where to go from here

sortedItems: Ember.computed.sort('filteredItems',function(a,b){
  if(a.get('winning') == true && a.get('winning') != b.get('winning')){
    return -1;
  }
  if(a.get('winning') == b.get('winning')){
    return 0;
  }
  if(a.get('winning') == false && a.get('winning') != b.get('winning')){
    return 1;
  }
}),

Upvotes: 2

Views: 129

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

I suggest to use a sorting function like this. It sorts by grouping the bid status.

function (a, b) {
    var status = { winning: 1, bidding: 2, closed: 3, watching: 4 };
    return status[a.bidStatus] - status[b.bidStatus];
}

Upvotes: 2

Majeed Siddiqui
Majeed Siddiqui

Reputation: 548

consider winning = 0, bidding = 1, watching = 2, closed = 3

    var arrayOfBids = [a, b, c, d, e, f];

    arrayOfBids.sort(function(bid1, bid2) {

        return getBidStatusVal(bid1.status) - getBidStatusVal(bid2.status);

        function getBidStatusVal(bidStatus) {
           switch(bidStatus) {
             case "winning": return 0;
             case "bidding": return 1;
             case "watching": return 2;
             case "closed": return 3;
             default: return 4;
           }
        }
    });

Upvotes: 0

Related Questions