Cracker0dks
Cracker0dks

Reputation: 2490

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

Upvotes: 3

Views: 251

Answers (2)

UweB
UweB

Reputation: 4110

There is no special jQuery.sort method, it will use the standard javascript native sort function. This one sorts arrays, you're trying to sort an object.

However, e still isn't sorted - it's the chrome console, which always lists the properties of your object alphabetically.

If you change

var e =  $(o).sort();

to

var e = $(o);

, the console output will still be the same.

Upvotes: 1

jAndy
jAndy

Reputation: 235962

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

Upvotes: 4

Related Questions