-1

So I am trying to sort an array of objects by both their priority and their position.

This is an example of the data I am trying to sort:

widgetInfo = [
    {name: 'box1', position: 'mobile-top', priority: 'priority-1'}, 
    {name: 'box2', position: 'mobile-top', priority: false}, 
    {name: 'box3', position: 'mobile-top', priority: 'priority-2'}, 
    {name: 'box4', position: false, priority: false}, 
    {name: 'box5', position: 'mobile-bottom', priority: false}
];

What I want to be able to do is to get them in order so the objects that have a position of mobile-first are first, followed by those with a position of false and lastly followed by those with a position of mobile-bottom.

Then of the ones that have mobile-top, I want to sort those in order of priority, so the mobile-top with priority-1 appears above the mobile-top, priority-2.

So the data would come out like:

widgetInfo = [
    {name: 'box1', position: 'mobile-top', priority: 'priority-1'}, 
    {name: 'box3', position: 'mobile-top', priority: 'priority-2'}, 
    {name: 'box2', position: 'mobile-top', priority: false}, 
    {name: 'box5', position: false, priority: false}, 
    {name: 'box4', position: 'mobile-bottom', priority: false}
];

I understand I can use the underscore sortBy function and to sort by a string name of the property but is there a way to use it to do what I am after?

My question is different to Underscore: sortBy() based on multiple attributes in the fact I am not after ordering alphabetically or numerically but in a specific order so that mobile-top is first, followed by the false entries followed by the mobile-bottoms and then sorted inside these.

Community
  • 1
  • 1
Tenatious
  • 849
  • 4
  • 12
  • 32
  • http://stackoverflow.com/questions/16426774/underscore-sortby-based-on-multiple-attributes – TryingToImprove Mar 06 '15 at 10:43
  • This doesn't answer my question as I am not trying to sort alphabetically or by number. I need them to appear in a certain order with the mobile-tops first, then the false and then the mobile-bottoms. – Tenatious Mar 06 '15 at 10:47

1 Answers1

2

Based on this answer https://stackoverflow.com/a/18262813/1071630 and on the expansion given in http://blog.falafel.com/nifty-underscore-tricks-sorting-by-multiple-properties-with-underscore/ taking advantage of the stability of _.sortBy, you could chain the sortBy, converting the enumerated values to a number. Something like

var sorted = _.chain(widgetInfo)
.sortBy(function(box) {
   if (box.priority === false)
       return Number.POSITIVE_INFINITY;
   else
       return +box.priority.substr(9);
})
.sortBy(function(box) {
    switch(box.position) {
        case 'mobile-top' : return 0;
        case false : return 1;
        case 'mobile-bottom' : return 2;
        default: return 3;
    }
})
.value();

And a demo http://jsfiddle.net/nikoshr/yg37188n/

Community
  • 1
  • 1
nikoshr
  • 32,926
  • 33
  • 91
  • 105