CFLib.org – Common Function Library Project

arrayReduce(array, callback)

Last updated July 31, 2013

author

Adam Cameron

Version: 1 | Requires: CF9 | Library: CFMLLib

Description:
Similar to Javascript's one ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Return Values:
The result of the reduction. Can be any data type

Example:

function add(required numeric currentValue, required numeric index, required array array, numeric previousValue){
    return previousValue + currentValue;
}


result = arrayReduce([1,2,3,4], add, 0);

writeDump([result]);

Parameters:

Name Description Required
array Array to reduce Yes
callback Callback function to use to reduce. Will receive the following arguments: element (of current iteration of the all), index, array, (optional) result (of preceeding call to callback()) Yes

Full UDF Source:

/**
 * CFML implementation of Array.reduce()
 * v1.0 by Adam Cameron with assistance from Adam Tuttle and Russ Spivey
 * 
 * @param array      Array to reduce (Required)
 * @param callback      Callback function to use to reduce. Will receive the following arguments: element (of current iteration of the all), index, array, (optional) result (of preceeding call to callback()) (Required)
 * @return The result of the reduction. Can be any data type 
 * @author Adam Cameron (dac.cfml@gmail.com) 
 * @version 1.0, July 31, 2013 
 */
public any function arrayReduce(required array array, required any callback, any initialValue){
    var startIdx = 1;
    if (!structKeyExists(arguments, "initialValue")){
        if (arrayLen(array) > 0){
            var result = callback(array[1], 1, array);
            startIdx = 2;
        }else{
            return;
        }
    }else{
        var result = initialValue;
    }
    for (var i=startIdx; i <= arrayLen(array); i++){
        result = callback(array[i], i, array, result);
    }
    return result;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson