var items = [ { firstname: 'Lazslo', lastname: 'Jamf', accountType: 'Gold'}, { firstname: 'Barack', lastname: 'Obamo', accountType: 'Platinum' }, { firstname: 'Pig', lastname: 'Bodine', accountType: 'Silver'}, { firstname: 'Pirate', lastname: 'Prentice', accountType: 'Platinum' } ];
Here, items is an object we need to sort by it's property 'accountType' and the sortOrder array is the predefined order it should follow. The order will be, first Platinum then Gold and then Silver.
Solution:
items.sort(function(a, b) { return sortOrder.indexOf(a.accountType) - sortOrder.indexOf(b.accountType); });
So the final result will be,
var items = [ { firstname: 'Barack', lastname: 'Obamo', accountType: 'Platinum' }, { firstname: 'Pirate', lastname: 'Prentice', accountType: 'Platinum' } { firstname: 'Lazslo', lastname: 'Jamf', accountType: 'Gold'}, { firstname: 'Pig', lastname: 'Bodine', accountType: 'Silver'} ];