Javascript sort callback

10,021

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
Share:
10,021

Related videos on Youtube

Author by

gyosko

Student,Gamer,Baller,very curious and lots more! :) My starcraft 2 Profile : Scamuso My Twitter: gyosko

Updated on June 04, 2022

Comments

  • gyosko 7 months

    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 do is to call a function when the sort function is done.

    Is it possible to add a callback function to sort or to trigger an event when when sort is over?

    • E. Sundin
      E. Sundin about 7 years
      You can just add the function to call after you've sorted the list.
    • Felix Kling
      Felix Kling about 7 years
      .sort() is synchronous.
    • RobG
      RobG about 7 years
      As suggested, you can do arr.sort(comparefn).arrMethod() or someFn(arr.sort(comparefn)) since sort returns the sorted object.
  • grim
    grim about 7 years
    @epascarello just for the hell of it :P And I figured I'd make it a prototype just to show how this can be done.
  • RobG
    RobG about 7 years
    Consider replacing resultFunction(result) with resultFunction.apply(result, arguments) to allow arguments to be passed to resultFunction. But extending built–ins isn't a good idea.