0

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.logs 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?

Vincent
  • 4,876
  • 3
  • 44
  • 55
  • Oops! For anyone coming across this later: the `JSON.stringify` I added here to format it more easily for StackOverflow actually prevented this issue from showing up, the reason for which is explained in the answer to the duplicate. – Vincent Sep 24 '18 at 09:45
  • What's the problem here, objects are being printed in the correct order only. – Prometheus Sep 24 '18 at 09:47
  • Although I haven't looked at the dupe target, I believe this is because a console log is evaluated live. I.e. it's not a snapshot. – evolutionxbox Sep 24 '18 at 09:47
  • @Prometheus the order is correct, but the log shows the sorted array which was called after the log. – evolutionxbox Sep 24 '18 at 09:47
  • @Prometheus I explained that in my first comment. The order is correct because I called `JSON.stringify` here, which I didn't do when I first encountered this issue. – Vincent Sep 25 '18 at 10:33

0 Answers0