Description

This function iterates over each row of a query and calls the closure function to work on the row of the query. This function reduces the query to a single value that would be returned.

Returns

The result returned by the last invocation of reduce function (with the last row).

Category

Query functions

History

New in Adobe ColdFusion (2016 release)

See also

QueryMap

Syntax

Object QueryReduce(Object query , UDFMethod reduceFunc [, Object initialValue])

Parameters

Parameter Description
query (Required) The query to be iterated over.
reduceFunc (Required) The reduce function to be called with each row of the query.
initialValue (Optional) The value to be passed to reduce function for the first row.

Example

<cfscript>
               qoptions = {result="myresult", datasource="cfbookclub", fetchclientinfo="yes"};
               sampleQuery = QueryExecute("select * from books order by bookid", [] ,qoptions);
               
               temp = "";
               titles = QueryReduce(sampleQuery, function(temp, element){
                              temp = temp?:"";
                              temp = temp & element.TITLE & " | ";
                              return temp;
               });
               writeOutput(titles);
</cfscript>

The script returns a string of appended titles.

Using member function

<cfscript>
       myResult=QueryExecute("SELECT * FROM EMPLOYEES",[],{datasource="cfdocexamples"});
       myArray=ArrayNew(1);
       
       // Populate myArrray with random values between 25-45
       for (i=1;i<=myResult.recordcount;i++){
             myArray[i]=randrange(25,45);
             
       }
       // Add column Ages and populate with values of myArray
       QueryAddColumn(myResult,"Ages","integer",myArray);
       
       // Use reduce function to calculate the average age of all persons in the recordset
       // Initialize age in closure
       status=myResult.reduce(function(age=0,col){
             return age+col.Ages/myResult.recordcount;
       });
       
       WriteOutput(status);
</cfscript>

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License  Twitter™ and Facebook posts are not covered under the terms of Creative Commons.

Legal Notices   |   Online Privacy Policy