Sorting an Array of JavaScript Objects a Specific Order (using existing function) Sorting an Array of JavaScript Objects a Specific Order (using existing function) arrays arrays

Sorting an Array of JavaScript Objects a Specific Order (using existing function)


Just use indexOf to convert the key to the correct order:

var order = ["c", "a", "b", "d"];_.sortBy(arr, function(obj){     return _.indexOf(order, obj.key);});

Fiddle

If there are a lot of keys, then it would be advantageous to make a hash-map out of the array, like:

var order = ["c", "a", "b", "d"];var orderMap = {};_.each(order, function(i) { orderMap[i] = _.indexOf(order, i); });

This makes the key-sorting lookup constant time rather than O(n). (Fiddle)


Great answers provided so far. Thought that the following may also be an alternative solution in plain JS:

var arr = arr.sort(function(a,b) {    return order.indexOf( a.key ) - order.indexOf( b.key );    //for the sake of recent versions of Google Chrome use:    //return a.key.charCodeAt(0) > b.key.charCodeAt(0); or return a.key.charCodeAt(0) - b.key.charCodeAt(0);});