0

I know you're not supposed to sort javascript objects but I need to for a d3 chart. I have an object with a key of FICO score ranges and value of the count of how many in that range

var counts = {680-700: 30, 620-640: 41, 640-660: 24, 660-680: 10}

I need to return a sorted object such that the lowest value keys come first.

var desired_obj = { 620-640: 41, 640-660: 24, 660-680: 10, 680-700: 30  }

I attempted to use _.sortBy but it only returns the values

 _.sortBy(counts, function(val, key) { return val })
user2954587
  • 4,661
  • 6
  • 43
  • 101
  • 1
    Post your chart-making code: where do you need a sorted dictionary? A JavaScript object has no order, so sorting it makes no sense. – nwk Jan 14 '15 at 18:37
  • 3
    Is there a reason `counts` can't be an array? e.g. `[{range: '680-700', count: 30}, {range: '620-640', count: 41}, {range: '640-660', count: 24}, {range: '660-680', count: 10}]` – Shawn Bush Jan 14 '15 at 18:42
  • @shawnb no, that would be fine – user2954587 Jan 14 '15 at 18:54
  • 2
    @shawnb got it. thanks for pointing me in the right direction. I used `var map = _.map(counts, function(val, key) { return {label: key, value: val } )` and then sorted `_.sortBy(map, function(x) { return x.label.split("-")[0] })` – user2954587 Jan 14 '15 at 19:03

1 Answers1

0

As discussed in the comments, JavaScript objects explicity have no order in the keys. (Source: https://stackoverflow.com/a/5525820/1007263)

If you need to ensure order, you must convert your object into an array. You can do that easily with underscore:

a = {a:1, b:3, c:2}
_.map(a, function(value, key) { return {key: key, value: value} })
// [{"key":"a","value":1},{"key":"b","value":3},{"key":"c","value":2}]

And you can use chain to sort after mapping:

_.chain(a).map(function(value, key) { return {key: key, value: value} }).sortBy('value').value()
//"[{"key":"a","value":1},{"key":"c","value":2},{"key":"b","value":3}]"
Community
  • 1
  • 1
Guilherme Rodrigues
  • 2,818
  • 1
  • 17
  • 22