I'm confused about the difference between the output for the following two pieces of code:
var x = [{'size': 3}, {'size': 2}, {'size':1}];
console.log("Before I sort, x is", x);
x.sort(function(a, b) {
console.log("Sorting x…");
return a.size - b.size;
});
console.log("After I sort, x is", x);
yields
…which is surprising since the "Before I sort…" array seems sorted. If I remove the sort
, i.e. run
var x = [{'size': 3}, {'size': 2}, {'size':1}];
console.log("Before I sort, x is", x);
// x.sort(function(a, b) { console.log("Sorting x…");
// return a.size - b.size; });
// console.log("After I sort, x is", x);
Then I see what I expect in the first console.log
,
Confused by this, I tried printing out x[0]
as well, which is correct, even though the display of x
is not, i.e.
var x = [{'size': 3}, {'size': 2}, {'size':1}];
console.log("Before I sort, x[0] is", x[0], "and x is", x);
x.sort(function(a, b) { console.log("Sorting x…");
return a.size - b.size; });
console.log("After I sort, x[0] is", x[0], "and x is", x);
yields
…which seems inexplicable, since the printed x
's are the same, even though x[0]
is not.
What gives? How can I explain this behavior?
I hope it doesn't matter, but I'm running this on Google Chrome 69.0.3497.100 (Official Build) (64-bit)
Thanks!