Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Re: How to sort a JS Object?</p> <p>Answer: You can't. So instead, you need a more sophisticated data structure. You have many options:</p> <ol> <li>You can use a separate array to hold the order of the object's keys. (This is what @Felix Kling's answer demonstrates.) Good: fast retrieval via order or name. Bad: needs a second data structure that must be kept synched with the first.</li> <li>Instead of the Object simply holding properties and values, the properties could hold Objects which hold the values and a sort order. Good: 1 data structure. Fast lookup by property name. Bad: slow lookup by order (need to scan the structure). Slow sorting.</li> <li>Use an array, with elements consisting of Objects that hold the key and the value. Good: 1 data structure. Fast lookup by order. Fast sorting. Bad: slow lookup by property name (need to scan the structure).</li> </ol> <p>I recommend solution 3 since it uses the JS mechanics to manage the ordering.</p> <p>Examples:</p> <pre><code>// Object holds sort order: (Solution 2) var foo = { Suzy: {v: 4, order: 0}, Billy: {v: 5, order: 1}, Jimmy: {v: 2, order: 2}, Sally: {v: 1, order: 3} }; // Array holds keys: (Solution 3) var woof = [ {k: 'Suzy', v: 4}, {k: 'Billy', v: 5}, {k: 'Jimmy', v: 2}, {k: 'Sally', v: 1} ]; // Sort the woof array by the key names: woof.sort(function(a, b) { return a.k.localeCompare(b.k); }); // The third key and value: woof[2].k; // the third key woof[2].v; // the third value </code></pre> <p>Edited: updated code to fix typo. Thank you, @Martin Fido</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload