thats the code i typed in chrome console:
var o = { "B": "2", "A": "1", "C": "3" };
var e = $(o).sort();
And thats the results (console.log)
Object {B: "2", A: "1", C: "3"} //Output for: console.log(o);
// output for console.log(e);
[Object, jquery: "1.10.1", constructor: function, init: function, selector: "", toArray: function…]
0: Object
A: "1"
B: "2"
C: "3"
...
Object {B: "2", A: "1", C: "3"} //output console.log(e[0]);
can someone tell me how i get the sorted object, and why is the Object in e sorted and e[0] is not ?
Thank you :)
jQuery won't apply a sort on a normal object just like that. Even if it abstracts the Array.prototype.sort method into its own collections, it doesn't work like that out of the box. jQuery expects DOM nodes to be in there, but even if thats the case, you need to at least define a custom sort function which you pass into .sort() to make it work.
You might know that object keys do not have any guaranteed order in ECMAscript. So we can only sort its keys "statically" as Array and then access the object with that sorted list of key names.
For instance
var o = { "B": "2", "A": "1", "C": "3" };
var sortedKeys = Object.keys( o ).sort();
console.log( sortedKeys ); // ["A", "B", "C"]
Of course, we could directly access the object invoking Array.prototype.forEach, like
Object.keys( o ).sort().forEach(function( key ) {
console.log( o[ key ] );
});
Would output: 1, 2, 3
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