Sort objects by 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 a wipe type should have the highest priority, so it should be in front of the array (index = 0).

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

For example,

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? } 
+8
javascript sorting algorithm
source share
3 answers

JavaScript array.sort method expects a comparison function, just pass this function:

 function compareFunc(a,b) { return animPriority[a.type] - animPriority[b.type]; } 
+3
source share

This may 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 on demand. See this jsfiddle for proof.

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

+16
source share

This is pretty simple in JavaScript:

First put the objects in an array, for example. myArray

Then 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 both objects are equal for sorting purposes 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 your array. If you need a more detailed example using your specific data, just ask.

+3
source share

All Articles