Simple question d3.js sorting key/value pairs alphabetically by value

1,642 views
Skip to first unread message

Jim Gwilliam

unread,
Sep 27, 2013, 1:13:11 AM9/27/13
to d3...@googlegroups.com
I have an object of the form....

Object {win_pct_r"Winning %"n_losses_r"Losses"n_wins_r"Wins"pp_fd_td_o"% Plays (TD or FD)"n_int_o"Interceptions Thrown"}

I want to sort this object of key/value pairs alphabetically by "VALUE", maintaining the key/value pair relationship.

I've tried the following:     a = d3.entries(statkeyvalues).sort(d3.ascending()).map(function(d) {return d.value;})

But it doesn't seem to return the proper result.

Any suggestions?


Thanks,
Jim

phoebebright

unread,
Sep 27, 2013, 6:59:34 AM9/27/13
to d3...@googlegroups.com
Will the standard sort function work?

        sorted =  myobject.sort(function(a,b) {
                if (a['VALUE'] < b['VALUE'])
                    return -1;
                if (a['VALUE'] > b['VALUE'])
                    return 1;

                return 0;
                });

nick

unread,
Sep 27, 2013, 9:49:51 AM9/27/13
to d3...@googlegroups.com
Or the slightly more concise:

d3.entries(statkeycolumns).sort(function(a, b){
  return -a.value.localeCompare(b.value);
}))

To use d3.ascending, you'd need to wrap it up to pluck out the right key-value, maybe like this:

function keySort(sortfunc, field){
  return function(a, b){
    return sortfunc(a[field], b[field]);
  }
}

d3.entries(statkeycolumns).sort(keySort(d3.ascending, "value"));

If you only ever bind them to one selection, you can do this inline:

d3.selectAll("div")

  .data(columns)
  .call(function(init){
    init.enter().append("div");
  })
  .sort(function(a, b){
    return -a.value.localeCompare(b.value);
  })
  .text(function(d){ return d.value; });

But if you are going to use the list somewhere else where order is relevant, you'll want to sort the entries array itself.

I hope one of these helps!
Reply all
Reply to author
Forward
0 new messages