1

What are the arguments of "compareFunction" in sort of Array in JavaScript? If you notice the second argument, it comes in randomly not in any particular order. Whereas the first argument is always in the current order. I want to know how is the second argument choosen.

arr.sort(compareFunction)

1 Answer 1

3

You can make no assumptions at all about how or why the sort mechanism passes parameters. It's not in the specification, and the JavaScript runtime is free to implement the sort any way it wants. It's not even required that the same sort mechanism be used in all cases.

The comparator function should simply compare the two elements and return a numeric result. Furthermore, a proper comparison function should be consistent: for any pair of elements (in either order), the result of calling the comparison function should reflect the same ordering. The function should be transitively consistent as well. The comparison function should not make any changes to the list being sorted. If the comparison function does not satisfy those conditions, the result of the sort operation is implementation-defined (ie, you can't rely on any particular result).

Sign up to request clarification or add additional context in comments.

2 Comments

It is (at least partially) in the spec for some cases.
@Quentin I'm not sure I see anything that stipulates any pattern for pairs of elements passed to the function, other than that the sort process should not pass undefined elements.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.