0

I know that's function:

function myFunction() {
points.sort(function(a, b){return a - b});

is fully working for sorting array contain number in ascending..

If the result is negative a is sorted before b.

If the result is positive b is sorted before a.

If the result is 0 no changes are done with the sort order of the two values.

But how's the sequence for the compare "a" and "b" ? Is it "index0" compare "index1", then "index1" compare "index2", etc..? I just don't understand this "compare function" workflow/ sequence...

1 Answer 1

0

It is unspecified. The specification says:

  1. Perform an implementation-dependent sequence of calls to the Get, Set, DeletePropertyOrThrow, and HasOwnProperty abstract operation with obj as the first argument, and to SortCompare (described below), such that:
  2. ...

Because this order is unspecified, we used to be able to see behaviors like this, in which an inconsistent sort algorithm results in different sorting results in different environments, because the different environments were comparing array items in different orders.

If you do have a stable, consistent sorting algorithm, then the order in which items are compared should not matter, especially given that sorting is now supposed to be stable as of ES2019 ("that is, elements that compare equal must remain in their original order").

No matter the order in which the engine compares items, the resulting array should be the same across environments. It may compare item [0] against item [1]first, or it may compare item [length - 1] against item [length - 2] first.

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

Comments

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.