1

If I have an object like this how can I sort using the underscore module in node.js so the values are highest to lowest so that...

 { ZZX: 1, FRA: 5, GBR: 2, USA: 3 }

..becomes

{ FRA: 5, USA: 3, GBR: 2, ZZX: 1 }
NewToJS
  • 1,635
  • 3
  • 22
  • 47
  • 2
    This might help http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value – SteamDev Jul 05 '16 at 17:28
  • 4
    [There's no guaranteed key order for JavaScript objects](http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) so you probably need an array to accommodate this. – tadman Jul 05 '16 at 18:07
  • A posible fix : `var obj = { FRA: 5, USA: 3, GBR: 2, ZZX: 1 }; var keys = Object.keys(obj).map(e=>({ country: e, score : obj[e] })).sort((a, b)=>b.score - a.score); keys.map(JSON.stringify).forEach(alert);` – Jose Hermosilla Rodrigo Jul 05 '16 at 18:28

1 Answers1

0

You can do

sortedKeys = _.sortBy(Object.keys(obj), function(key){ return obj[key]; }).reverse();
newHash = {};
sortedKeys.forEach (e => (newHash[e] = obj[e]));
console.log(newHash)