18
String.prototype.width = function(font) {

  var f = font || '12px arial',
      o = $('<div>' + this + '</div>')
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}


function sortCustomFunction(a, b) {
  if (a['text'].width() < b['text'].width())
     return -1;
  if (a['text'].width() > b['text'].width())
     return 1;
  // a must be equal to b
  return 0;
}

var annoObj = {
        'anno' : [
            //an paikseis me auta (px to teleutaio na mpei prwto kok) oi mikres metatwpiseis ofeilontai sto padding.
            { "label" : "fifth" , "text"  : "This is a sample text another one" , 'color' : 'red' },
            { "label" : "first" , "text"  : "This is a sample" , 'color' : 'grey' },
            { "label" : "second" , "text" : "sample" , 'color' : 'green' },
            { "label" : "sixth" , "text"  : "This is a sample text another one text one mooooorreee" , 'color' : 'lightgreen' },
            { "label" : "third" , "text"  : "another one" , 'color' : 'blue' },
            { "label" : "forth" , "text"  : "one mooooorreee" , 'color' : 'purple' }        
        ]
    };

    console.log(annoObj.anno);   //This should print the unsorted array (but it prints the sorted array).
    annoObj.anno.sort(sortCustomFunction); //Sort the array
    console.log(annoObj.anno);  //This should print the sorted (and it does)

I'm doing the above and everything works fine. The array inside the json object is sorted by the width value of the 'text' key in the json elements of the array. What I noticed is this odd behavior in console.log. I'm printing the array before sorting and after sorting and in both prints it's the same. It prints the sorted array. Why is this?

JSFIDDLE

Alkis Kalogeris
  • 17,044
  • 15
  • 59
  • 113
  • exact duplicate of [Is Chrome's JavaScript console lazy about evaluating arrays?](http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) – Bergi Jun 26 '13 at 12:41
  • I didn't know this command (newbie in javascript). Thank you. Post it as an answer I will upvote. – Alkis Kalogeris Jun 26 '13 at 12:43
  • 2
    Btw, you really should get the `.width()` of every string only once - it's a quite heavy computation. – Bergi Jun 26 '13 at 12:43
  • @Bergi thanks for the suggestion. It's part of a bigger program and I'm building a demo for now. Customization will come later. – Alkis Kalogeris Jun 26 '13 at 12:44
  • @Bergi you are right, I searched but I didn't use the right words I guess because I was lost in the suggestions. – Alkis Kalogeris Jun 26 '13 at 12:47
  • I kept the topic because the suggestion console.table doesn't exist in the other one. I'm changing the title to be a little easier to find. – Alkis Kalogeris Jun 26 '13 at 12:52
  • @alkis: You probably would rather have found [some of its duplicate questions](http://stackoverflow.com/questions/linked/4057440?lq=1) - that particular title is too sophisticated to find without knowing it :-) – Bergi Jun 26 '13 at 12:54
  • Damn... I really searched though, maybe not too hard I guess. Anyway I will be more careful next time. – Alkis Kalogeris Jun 26 '13 at 12:57

3 Answers3

38

You have no problem with the sort but this is a well known peculiarity (an optimization) of most browser consoles : the tree is only built when you open the object, with the new values of the object.

If you want to see the state of the object at the time of logging, supposing it's a small enough and not self referencing object, you may clone it like this :

console.log(JSON.parse(JSON.stringify(annoObj.anno)));
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    Note that if you really need to log big and recursive objects, you also have a solution : [JSON.prune.log](https://github.com/Canop/JSON.prune). But most often you can limit your logs to a small enough part. – Denys Séguret Jun 26 '13 at 12:42
  • In case anyone is curious this is the actual recommended way to print out objects since more browsers do a live update of the object. [Read more in the Mozilla Documentation.](https://developer.mozilla.org/en-US/docs/Web/API/Console/log#logging_objects) – Felipe Centeno Feb 15 '22 at 23:13
0

I was answering a duplicated question of this one when that was was closed. Just as a related note of interest, Stackoverflow's code snippets do print the actual current value of the object, without the browser's bug.

let dummyArr = [
    {"name" : "a", "isChecked" : true},
    {"name" : "b", "isChecked" : false},
    {"name" : "c", "isChecked" : true}
];

console.log(dummyArr);
document.getElementById('a').innerHTML = JSON.stringify(dummyArr);

for(var i = 0; i < dummyArr.length ; i++){
    dummyArr[i].isChecked = false;
}

console.log(dummyArr);
document.getElementById('b').innerHTML = JSON.stringify(dummyArr);
<div id="a"></div>
<div id="b"></div>
alotropico
  • 1,904
  • 3
  • 16
  • 24
-2

Use console.table for tabular layout. Supported in Firebug and latest versions of Google Chrome.

https://developers.google.com/chrome-developer-tools/docs/tips-and-tricks#console-table

claustrofob
  • 5,448
  • 2
  • 19
  • 22