0

I want to sort my Javascript object descending, but all solutions I see makes them into arrays (which I don't want). Here is my object:

var obj = {
    "and":2,
    "two":1,
    "too":1,
    "mother":3
}

I want this object to look like this instead:

var obj = {
    "mother":3
    "and":2,
    "two":1,
    "too":1
}

The property's name sorting doesn't matter, so I don't care about it being two,too. All I care about is the property's value being sorted. An ES6 friendly one-liner would be great, but it's definitely not required.

Thanks.


EDIT: I finally got something working, although it's really, really bad.. really bad.

function sortObject(obj) {
    var sortable=[];
    var newObject = {};
    for(var key in obj)
        if(obj.hasOwnProperty(key))
            sortable.push([key, obj[key]]); // each item is an array in format [key, value]
    sortable.sort(function(a, b) {
        return b[1]-a[1];
    });
    for(i = 0; i < sortable.length; i++) {
        newObject[sortable[i][0]] = sortable[i][1];
    }
    return newObject;
}

I mean yeah it works, that's all that matters.

MortenMoulder
  • 6,138
  • 11
  • 60
  • 116
  • 5
    Object properties hold no order, so "sorting" an object makes no sense. You could just sort the array of keys. – Sirko Aug 08 '16 at 21:08
  • And why would you want this ? – Rayon Aug 08 '16 at 21:09
  • `srt=a=>{var o={};Object.keys(a).map(b=>o[b]=a[b]); return o} ; srt({b:1,a:2});` – dandavis Aug 08 '16 at 21:09
  • 1
    Why would you want to do such a thing? Can you explain your motivation behind this question? – Steve Aug 08 '16 at 21:09
  • 1
    @Sirko: you are wrong, objects keep non-integer keys in insertion order. if you want to mutate, you can rewrite the above snip with `delete` to re-insert on an existing object... – dandavis Aug 08 '16 at 21:09
  • I want to plot these objects into charts. Highest number and its property name being next to it. – MortenMoulder Aug 08 '16 at 21:09
  • @Snorlax: That's what an array is for. – T.J. Crowder Aug 08 '16 at 21:11
  • i often use object key ordering to make API response show the important keys first... – dandavis Aug 08 '16 at 21:11
  • @dandavis - are you saying objects **do** have order ? – adeneo Aug 08 '16 at 21:12
  • @dandavis Objects have no reliable order. But some methods like `Object.getOwnPropertyNames` do sort the properties. Other methods like `Object.keys` or `for...in` do not. – Oriol Aug 08 '16 at 21:12
  • yeah, insertion order. officially since ES6 and realistically since Chrome5, with some minor exceptions. – dandavis Aug 08 '16 at 21:13
  • @dandavis See [Does ES6 introduce a well-defined order of enumeration for object properties?](http://stackoverflow.com/q/30076219/1529630) The answer is still "no". – Oriol Aug 08 '16 at 21:13
  • [_Sort Map/Hash by values, retaining keys_](http://stackoverflow.com/questions/36079323/sort-map-hash-by-values-retaining-keys) – Rayon Aug 08 '16 at 21:13
  • [_How to sort object by number of properties in Javascript?_](http://stackoverflow.com/questions/38144234/how-to-sort-object-by-number-of-properties-in-javascript) – Rayon Aug 08 '16 at 21:14
  • @dandavis As I'm too lazy to search for the exact part of the spec, I refer you to http://stackoverflow.com/a/5525820/1169798 . You here rely just on a implementation specific detail, which may change at any point. – Sirko Aug 08 '16 at 21:14
  • well i wouldn't want to have order be make or break, but i find it reliable in practice to enhance literal presentation and pre-sort some naive template engine outputs. does my snip look ok in the console or not? we can argue semantics and specs, or we can just test the 1-liner to see how your system behaves. now if you want to talk about cross-platform order, that's a different beast... – dandavis Aug 08 '16 at 21:15
  • @Oriol: i find `Object.getOwnPropertyNames()` output unsorted, just like `Object.keys()` are we waiting on ES rollout? – dandavis Aug 08 '16 at 21:23
  • So what you guys say is that it's impossible? I find that hard to believe :O – MortenMoulder Aug 08 '16 at 21:27
  • @dandavis If `Object.getOwnPropertyNames` does not sort the result your implementation is not ES6 compliant. First there should be integer indices in ascending numeric index order, and then other string properties in property creation order. `Object.keys` is not required to do that, but sometimes might use the same order, on some implementations. – Oriol Aug 08 '16 at 21:32
  • @Snorlax: it's worth a shot to improve UX if it prevents forking a complex tool, but if you're trying to mimic a structure from another language, you better be sure about all the middle-ware iteration and 1,000,001 pesky gotchas and complicated rules. – dandavis Aug 08 '16 at 21:41
  • @dandavis I'm not sure how I would do this otherwise. What I have is basically a list of words (a sentence even). What I want is to count the amount of occurrences of the same word (like `the hamster, the monster, the best` would show `the: 3`, `hamster: 1` and so on). That seems like the perfect thing to put into an object.. no? – MortenMoulder Aug 08 '16 at 21:43
  • for what you describe, i've always maintained it should work just fine, or at least not hurt... – dandavis Aug 08 '16 at 21:46
  • @dandavis So putting them inside an object is fine, but apparently it's impossible to sort an object on its property values? – MortenMoulder Aug 08 '16 at 21:50
  • well did my code help or not? if so then use it, if not, don't bother. – dandavis Aug 08 '16 at 21:51
  • @dandavis Well nope. It doesn't do anything except print out the same object as I give it (or just `{b:1,a:2}` as you wrote). – MortenMoulder Aug 08 '16 at 22:23
  • well there's your answer; some part of the chart making doesn't use a known order iteration... – dandavis Aug 08 '16 at 22:24
  • @dandavis w..what? The code you wrote doesn't even sort the object you wrote. My chart plotting works fine. – MortenMoulder Aug 08 '16 at 22:25
  • doh;`srt=a=>{var o={};Object.keys(a).sort().map(b=>o[b]=a[b]); return o} ; JSON.stringify(srt({b:1,a:2}));`; helps if you actually sort() ... – dandavis Aug 08 '16 at 22:36
  • @dandavis Kinda works now... At least with the object you provided. But nope: https://jsfiddle.net/8ak0snsw/ - Inline `srt({and:2,two:1,too:1,mother:3})` doesn't work either. – MortenMoulder Aug 08 '16 at 22:41
  • @dandavis (because you are sorting on the key not the value) – MortenMoulder Aug 08 '16 at 22:44
  • @dandavis I think you understood this wrong. I want to sort on the VALUE not the KEY. Not the PROPERTY but the PROPERTY VALUE. My example was pretty good and easy to understand. – MortenMoulder Aug 08 '16 at 23:21

0 Answers0