admin管理员组

文章数量:1244272

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?

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?

Share Improve this question asked Apr 14, 2016 at 10:09 ManuKarachoManuKaracho 1,2182 gold badges15 silver badges32 bronze badges 2
  • 1 how does your custom order depend on the array ? Is your array an already sorted list of types ? – VonD Commented Apr 14, 2016 at 10:11
  • @VonD the reference is a user depended sort order of available types – ManuKaracho Commented Apr 14, 2016 at 10:17
Add a ment  | 

1 Answer 1

Reset to default 18

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 es first.

Beware - this code have plexity 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).

本文标签: javascriptHow to sort an array of objects depending on a custom sort order using underscoreStack Overflow