根据特定规则对对象进行排序

saz*_*azr 8 javascript sorting algorithm

在Javascript中,我需要根据类型对数组中的对象进行排序.每种类型都具有更高的优先级,因此具有"擦除"类型的对象应具有最高优先级,因此位于数组的前面(index = 0).

排序这些对象的最佳方法是什么?是否有内置功能可以做到这一点?

例如:

function sortObjects( objs )
{
   // objs is an unsorted array of objects 
   var animPriority = {"wipe": 1, "fly": 2, "iris": 3, "flip": 4, "cube": 5, "blur": 6, "zoom": 7, "fade": 8, "glow": 9, "rotate": 10};

   for (var i=0; i<objs.length; i++)
       if (objs[i].type == "wipe")
          // bubblesort/bubbleswap element in objs[0] with objs[i]????
          // a bubble sort doesn't seem efficient though?
}
Run Code Online (Sandbox Code Playgroud)

Tad*_*eck 16

这可能是您正在寻找的解决方案:

objs.sort(function(a,b){
    var order = ["wipe", "fly", "iris", "flip", "cube",
        "blur", "zoom", "fade", "glow", "rotate"];
    return order.indexOf(a.type) - order.indexOf(b.type);
});
Run Code Online (Sandbox Code Playgroud)

它完全按照要求工作.请参阅此jsfiddle以获取证据.

该解决方案使用类的sort()方法Array,将回调传递给它,允许自定义比较.在这种情况下,比较基于数组.type中比较元素的属性位置order.


Lel*_*mbo 3

JavaScript 的array.sort方法需要一个比较函数,只需传递这个函数:

function compareFunc(a,b) { return animPriority[a.type] - animPriority[b.type]; }
Run Code Online (Sandbox Code Playgroud)