Given the following code:
const obj1 = { a: 2 };
const obj2 = { a: 3 };
const obj3 = { a: 1 };
const sortedArray = [obj1, obj2, obj3];
const unsortedArray = [obj1, obj2, obj3];
console.log('Sorted:', JSON.stringify(sortedArray));
console.log('Unsorted:', JSON.stringify(unsortedArray));
sortedArray.sort((one, two) => one.a - two.a);
I would expected both console.log
s to output the objects in the order they were defined - after all, sortedArray.sort
is only called after the console.log
, and as far as I know, the log is executed synchronously.
However, the actual output is:
Sorted:
[{"a":2},{"a":3},{"a":1}]
Unsorted:
[{"a":2},{"a":3},{"a":1}]
How come?