Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting objects according to a specific rule

In Javascript I need to order objects in an array according to type. Each type has a higher priority, so an object with the type "wipe" should have the highest priority therefore be at the front of the array(index=0).

What would be the best way to sort these objects? Is there a builtin function that can do this?

For eg:

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?
}
like image 556
sazr Avatar asked Dec 29 '11 01:12

sazr


2 Answers

This could be the solution you are looking for:

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);
});

It works exactly as requested. See this jsfiddle for a proof.

The solution uses sort() method of Array class, passing callback to it, which allows for custom comparison. In this case comparison is based on the position of .type property of compared elements within order array.

like image 128
Tadeck Avatar answered Oct 06 '22 18:10

Tadeck


It's pretty straightforward in JavaScript:

First, put your objects in an array, e.g. myArray.

Next, write a function that takes objects and returns a value less than 0 if the first object should appear before the second object in the array, 0 if the two objects are equal for purposes of the sort, or a value greater than 0 if the second object should appear before the first object in the array. For example:

function myOrderFunc(a, b)
{
  // if a should come before b, return a negative value
  // if b should come before a, return a positive value
  // if they are equally ranked in the sort order, return 0
}

Finally, call myArray.sort(myOrderFunc). This will sort the objects in place in your array. If you need a more detailed example using your specific data just ask.

like image 38
Paul Avatar answered Oct 06 '22 19:10

Paul