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?
}
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.
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.
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