Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of objects depending on a custom sort order using underscore

I have an array of objects

[
  {type:"foo",elements:[...]},
  {type:"bar",elements:[...]},
  {type:"any",[...]},
  {type:"some",elements:[...]}
]

I know how to sort that array by the attribute 'type' using underscore's _.sortBy() method.

But now I need a custom sort order which depends on another array:

["any","foo","some","bar"]

How would my sortBy callback have to look like to sort my objects by my custom order?

like image 471
ManuKaracho Avatar asked Apr 14 '16 10:04

ManuKaracho


1 Answers

It's easy:

_.sortBy(yourArrray, function(obj){
   return typesArray.indexOf(obj.type);
});

It sorts yourArray based on position of obj.type in typesArray. Types not present in array comes first.

Beware - this code have complexity O(kn log n). To improve it, use following code:

var yourTypes = {
   'any': 1,
   'foo': 2,
    'some': 3
}
_.sortBy(yourArrray, function(obj){
   return yourTypes [obj.type];
});

Object lookups are usually faster, resulting in O(1) access (and overall O(n log n) sorting).

like image 183
Ginden Avatar answered Oct 20 '22 08:10

Ginden