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.