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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With