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
1 Answer
Reset to default 18It'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).
版权声明:本文标题:javascript - How to sort an array of objects depending on a custom sort order using underscore - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740204141a2240754.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论