1

I have written a custom sorting routine (sortArray(a, b)) to sort an array that I have.

If I call it like this

    a.sort(function (v1, v2) { return sortArray(v1, v2); });

everything works fine.

If I call it like this:

    a.sort(sortArray(v1, v2));

v1 and v2 raise errors, as being undefined.

Is there no way to utilize arguments passed by the .sort() method without creating an anonymous function to initially receive them, and then to pass them on to a user-defined function?

1 Answer 1

6

Array.prototype.sort expects a function reference, but you are trying to call sortArray and pass the return value of that call. You should just pass a reference to your function:

a.sort(sortArray);

Since sortArray already expects two arguments, it should just work, v1 and v2 will be passed automatically.

2
  • What a clear response! That it wants a function reference absolutely turned on the light! Incidentally, it returns a number, and sorting is done in acordance with the sign of the returned number.
    – Brian Wren
    Jul 29, 2013 at 21:15
  • Glad to help, @BrianWren! You're right that the comparison function should return a number, I forgot that.
    – bfavaretto
    Jul 29, 2013 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.