Search code examples
sortingkeylodash

Lodash sorting object by values, without losing the key


Let's say I have an object:

{Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12}

And I need to sort it by value. What I'm looking to get is:

{Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2}

I'd like to use lodash for it. When I use _.sortBy it doesn't retain the keys how ever:

_.sortBy({Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12}).reverse();
// [17, 12, 8, 5, 2]

Hell, I'd even settle for just the array of keys, but still sorted by the value in the input:

['Derp', 'Herp', 'Foo', 'Asd', 'Qwe']

Solution

  • You could try like this,

    _.mapValues(_.invert(_.invert(obj)),parseInt);
    

    Object {Herp: 2, Asd: 5, Foo: 8, Qwe: 12, Derp: 17}

    or

    var obj = {Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12}
    
    var result = _.reduceRight(_.invert(_.invert(obj)), function(current, val, key){    
        current[key] = parseInt(val);
        return current;
    },{});
    

    Object {Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2}

    or Using Chain methods:

    _.chain(obj).invert().invert().reduceRight(function(current, val, key){ 
        current[key] = parseInt(val);
        return current;
    },{}).value()
    

    Object {Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2}

    Note: It depends on browser usally object properties order is not gurrantee in most case.