Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery sort result not consistent

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 :)

like image 254
Cracker0dks Avatar asked Feb 12 '26 07:02

Cracker0dks


1 Answers

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

like image 118
jAndy Avatar answered Feb 13 '26 22:02

jAndy