Double Sort (sorting by two variables) - works everywhere except Chrome

1,043 views
Skip to first unread message

Michael Wahlatlas

unread,
Apr 23, 2013, 1:56:48 PM4/23/13
to d3...@googlegroups.com
So I have a bar chart that I want to sort in two stages, by a categorial variable first (that's the color in the attached examples) and then within those values sort it by a continuous variable. Here's the code that works everywhere except Chrome

// adapts histogram bars
histog.selectAll("rect")

.sort(function(a, b) {
//return a.win > b.win?-1:1;
return d3.ascending(a.win, b.win);
  })
.sort(function(a, b) {
//return a.wkr > b.wkr?1:-1;
return d3.ascending(a.wkr, b.wkr);
  })

Using d3 version 3.1.5 the desired output will show in Safari 6.0.3, Firefox 20.0, IE 10.0.9 and IE 9.0.8 (see attached reference rendering "safari-firefox.png") but will not work in Chrome (Version 26.0.1410.65, OSX 10.8.3 - see attached "chrome.png").

Is this a misuse of sorting and should nesting be used here or is something wrong with Chrome?

Thanks very much for any help in advance
Michael
safari-firefox.png
chrome.png

Mike Bostock

unread,
Apr 23, 2013, 2:06:09 PM4/23/13
to d3...@googlegroups.com
You are assuming that sorting is stable, and this is not always the case. ECMAScript does not mandate that array.sort is stable, so Chrome chose to implement an unstable sort while Safari and Firefox are stable.


You should implement your comparator so that it doesn’t depend on the sort being stable. For example:

  array.sort(function(a, b) {
    return d3.ascending(a.wkr, b.wkr) || d3.ascending(a.win, b.win);
  });

Mike

Michael Neutze

unread,
Apr 23, 2013, 2:10:35 PM4/23/13
to d3...@googlegroups.com
Ah, thanks so much!
Where can we send the cookies :)

Michael
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "d3-js" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/d3-js/dB-95KpmROw/unsubscribe?hl=en.
> To unsubscribe from this group and all its topics, send an email to
> d3-js+un...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
Reply all
Reply to author
Forward
0 new messages