Skip to content Skip to sidebar Skip to footer

Javascript Sort Callback

I need to sort a big list of Javascript items and I'm using the sort function like this: var sorted_list = non_sorted.sort(function(a,b){ // Sort stuff here }); What I'd like to d

Solution 1:

You are overcomplicating it. The sort method isn't asynchronous, so you don't need a callback or an event. Just put your code after the code that calls sort:

var sorted_list = non_sorted.sort(function(a,b){
  // comparer
});
// The code just continues here after the sort

Solution 2:

The sort function is synchronous so you can simply do something right after the call but if you want another way:

Array.prototype.sortCallback = function(compareFunction, resultFunction){
    result = this.sort(compareFunction);
    resultFunction(result);
}

Usage:

non_sorted.sortCallback(function(a, b) {
  // Sort stuff here
}, function(sorted) {
   // Do something with the sorted array
});

Solution 3:

this is a little dirty but it works:

slow enough for the sort function (within reason) and faster than the naked eye.

function sort_with_callback() {

            run_sort_function();

            setTimeout(function() { run_callback()},  3);}

Post a Comment for "Javascript Sort Callback"