0

I have the following piece of code:

function() {
    $.getJSON(
        myurl + '/get_data',
        function(data) {
            function sort_data(first, second) {
                return (first.sort - second.sort);
            }
            console.log(data);
            console.log(data.sort(sort_data));
        }
        ... snipped for brevity

Data is array of objects, each object has sort field, which is integer. By default they are all in random order. So after executing the code above It tells me that data before and after sort is identical. At least both console.log outputs are the same (and they are sorted). However, if I skip the sorting part and just console.log(data.objects) - it's different and is unsorted.
It seems like sort is executed first, while console.logs are executed after. Why is it like that? Thanks!

konnigun
  • 1,797
  • 2
  • 17
  • 30

1 Answers1

3

it is because console.log() prints a reference to the object, and the sort() rearranges the data within the same object reference.

If you want to see the difference use

console.log(JSON.stringify(data));
console.log(JSON.stringify(data.sort(sort_data)));

JSON.stringify() creates a string representation of the json object, which will not affected by any further changes made to the json object.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • AIUI, recent versions of Chrome fixed this issue. – Alnitak Apr 25 '13 at 08:48
  • I see, it worked, thanks! But why exactly does my code show same data in both cases? Cause in first console.log(data) it didnt know yet that I am gonna sort data in next line. – konnigun Apr 25 '13 at 08:55
  • when you say ` console.log(data);` it print a reference to the memory location where the object is stored. when you sort the object the original object is modified so those changes will get reflected in the logged reference as well – Arun P Johny Apr 25 '13 at 08:58
  • @Chelios you can also have a look at the link posted by Alnitak – Arun P Johny Apr 25 '13 at 08:59
  • Interesting stuff, thanks! Got it – konnigun Apr 25 '13 at 09:01