alphanumeric sort

Ben Tilly btilly at gmail.com
Wed May 11 17:59:51 EDT 2011


In JavaScript the default sort order depends on the data types of the
variables in question.  If either is a string, you convert the other
to a string and sort lexicographically, but if both are numbers you
compare numerically.  There is a similar inconsistency around what the
"+" operation does.

Inconsistencies that can arise from string promotion are a common
source of surprise.

On Wed, May 11, 2011 at 1:35 PM, Alexander Sicular <siculars at gmail.com> wrote:
> Iirc, "sort()" is by default lexographic in JavaScript so an added function
> is not necessary. The added function is specifically intended for a custom
> sort, ie. numerical.
>
> You could simply do something like:
>
> return v['key'].sort()
>
> Try that out and lemme know if it works as you expect.
>
> Cheers ,
> Alexander
>
> @siculars on twitter
> http://siculars.posterous.com
>
> Sent from my iPhone
>
> On May 11, 2011, at 13:10, Claus Guttesen <kometen at gmail.com> wrote:
>
>>> Your compare function will need to return a -1, 0 or 1 for less than,
>>> the same or greater than.  Luckily javascript allows you
>>> to strings lexicographically so the function is a nice two liner:
>>>
>>> function(a, b) {
>>>  if(a == b) return 0;
>>>  return a > b ? 1 : -1;
>>> }
>>>
>>> Application:
>>>
>>> var reduceSort = function (v, args) {
>>>  return v.sort (function(a, b) {
>>>  if(a['key'] == b['key']) return 0;
>>>  return a['key'] > b['key'] ? 1 : -1;
>>>  });
>>> };
>>>
>>> Eric.
>>
>> Thank you so much! :-) Worked like a charm.
>>
>> --
>> regards
>> Claus
>>
>> When lenity and cruelty play for a kingdom,
>> the gentler gamester is the soonest winner.
>>
>> Shakespeare
>>
>> twitter.com/kometen
>>
>> _______________________________________________
>> riak-users mailing list
>> riak-users at lists.basho.com
>> http://lists.basho.com/mailman/listinfo/riak-users_lists.basho.com
>
> _______________________________________________
> riak-users mailing list
> riak-users at lists.basho.com
> http://lists.basho.com/mailman/listinfo/riak-users_lists.basho.com
>




More information about the riak-users mailing list