7

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?

2
  • 1
    how does your custom order depend on the array ? Is your array an already sorted list of types ? Commented Apr 14, 2016 at 10:11
  • @VonD the reference is a user depended sort order of available types Commented Apr 14, 2016 at 10:17

1 Answer 1

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 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).

Sign up to request clarification or add additional context in comments.

1 Comment

perfect answer. We will have only 10 different types, so it shouldn't matter performance wise - but thanks for the additional important information!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.