Here is some sample code:
var queryArr = [{ns: 42, pageid: 12, lang: "en", index: 3}, {ns: 12, pageid: 36, lang: "en", index: 4}, {ns: 2, pageid: 19, lang: "en", index: 9}];
console.log(queryArr);
queryArr.sort(function(i,j){
return j.index - i.index;
});
console.log(queryArr);
When I run this on the browser console, I got two console outputs, but both are sorted high to low. What I'm expecting is the first output to display the array exactly as I've entered it and the second, after the sort function to display it sorted the way I want.
Is the sort function executed before console.log? If so, how and why?
I've read these articles about hoisting because that's what I assume this is about (but I'm probably wrong):
- JavaScript variables hoisting in details
- JavaScript's lexical scope, hoisting and closures without myster
- Variable and Function Hoisting in JavaScript
But they all talk about mostly variable hoisting, and function declarations.
I'm hoping this isn't some browser related issue - I've run this code on Chrome and Firefox and they both produce the same results.