3

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

that helped me a lot! thank you for this professional asnwer :) i will use 2d arrays in this case.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.