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
The only notable difference between the two is that, when printing an object, console. log gives special treatment to HTML elements, while console.
Answer: Use console. log() or JSON. stringify() Method This method will print the object in browser console.
print will just print the text to console. console. log() actually records it and we can use it for many purposes like email it for bug report.
js, console. log() method is used to display the message on the console. By default, the console. log() method prints on console with trailing newline.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With