Skip to content

Sort an array by a preferred order

I’d like to come up with a good way to have a “suggested” order for how to sort an array in javascript.

So say my first array looks something like this:


Now all I care about, is that the sorted results starts out in this order:


After that, I Want the remaining values to be presented in their original order.

So I would expect the result to be:


I have an API that I am communicating with, and I want to present the results important to me in the list at the top. After that, I’d prefer they are just returned in their original order.

If this can be easily accomplished with a javascript framework like jQuery, I’d like to hear about that too. Thanks!

Edit for clarity:

I’d like to assume that the values provided in the array that I want to sort are not guaranteed.

So in the original example, if the provided was:


And I wanted to sort it by:


Since ‘david’ isn’t in the provided array, I’d like the result to exclude it.

Edit2 for more clarity: A practical example of what I’m trying to accomplish:

The API will return something looking like:

['Load Average','Memory Usage','Disk Space']

I’d like to present the user with the most important results first, but each of these fields may not always be returned. So I’d like the most important (as determined by the user in some other code), to be displayed first if they are available.



Something like this should work:

var presetOrder = ['jim','steve','david']; // needn't be hardcoded

function sortSpecial(arr) {
   var result = [],
       i, j;
   for (i = 0; i < presetOrder.length; i++)
      while (-1 != (j = $.inArray(presetOrder[i], arr)))
         result.push(arr.splice(j, 1)[0]);
   return result.concat(arr);

var sorted = sortSpecial( ['bob','david','steve','darrel','jim'] );

I’ve allowed for the “special” values appearing more than once in the array being processed, and assumed that duplicates should be kept as long as they’re shuffled up to the front in the order defined in presetOrder.

Note: I’ve used jQuery’s $.inArray() rather than Array.indexOf() only because that latter isn’t supported by IE until IE9 and you’ve tagged your question with “jQuery”. You could of course use .indexOf() if you don’t care about old IE, or if you use a shim.

User contributions licensed under: CC BY-SA
1 People found this is helpful