4

I am trying to use ColdFusion 2016 Query sort

I am basing the sort on Array sort by Raymond Camden

http://www.raymondcamden.com/2012/08/14/Another-ColdFusion-10-Closures-Post/

<cfscript>
    qryTest = QueryNew("ID,Name");
    qryTest.AddRow([ 
        {id=1,name="One"}, 
        {id=2,name="Two"}, 
        {id=3,name="Three"}, 
        {id=4,name="Four"} 
    ]);
    qryTest.sort(function(a, b) {
       return a.name > b.name;
    });
    writedump(qryTest);
</cfscript>

enter image description here

Is this a bug or am I doing it wrong? Or is sort member function not the same as QuerySort()

https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-m-r/querysort.html#main-pars_header

rrk
  • 15,677
  • 4
  • 29
  • 45
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
  • 1
    (Edit) Did you try replacing `>` or `<` with `compare()` like in the comments, so it returns -1,0 or 1, like with java comparators? – Leigh Feb 19 '16 at 19:02
  • 2
    Ppl might wanna go for for this ticket https://bugbase.adobe.com/index.cfm?event=bug&id=4119993 to get the docs improved so that they're actually helpful? – Adam Cameron Feb 19 '16 at 19:56

1 Answers1

6

Ray's example was for the CF10 beta. See this comment. In the CF10+ release, the comparator must return 1, 0, or -1.

Use this. When doing a.name > b.name it just returns true/false. You need to return 1/-1.

<cfscript>
    qryTest = QueryNew("ID,Name");
    qryTest.AddRow([ 
        {id=1,name="One"}, 
        {id=2,name="Two"}, 
        {id=3,name="Three"}, 
        {id=4,name="Four"} 
    ]);
    qryTest.sort(function(a, b) {
       return a.name > b.name ? 1 : -1;
    });
    writedump(qryTest);
</cfscript>

enter image description here

Leigh
  • 28,765
  • 10
  • 55
  • 103
rrk
  • 15,677
  • 4
  • 29
  • 45
  • 1
    Yes, that is pretty much what I mentioned in my earlier comment. Though not sure why it would work in CF10 ([it does *NOT* work on trycf.com](http://trycf.com/gist/405263637e37c77a3f6c/acf?theme=monokai)). It seems to be based on the [Comparator/Comparable](http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html) concept in java, ie return -1,0 or 1. That has been around for a while and has not changed much... – Leigh Feb 19 '16 at 19:17
  • *mentioned in my earlier comment* Oops, my bad. From the timestamps this answer was actually posted earlier. Darn notifications delay! Ah well, good thing I had already upvoted it :-) – Leigh Feb 19 '16 at 19:29
  • 2
    @Leigh: If I recall correctly... Ray's blog article was written during the CF10 *pre-release*. The implementation was buggy at the time. It was fixed before release. – Adam Cameron Feb 19 '16 at 19:49
  • 1
    @AdamCameron - Ah, that would explain it, because a simple `>` or `<` should not work in this context. I remember trying the same thing in java, getting the same *wrong* result .. and wondering why ;-) – Leigh Feb 19 '16 at 20:01