Search code examples
coldfusioncoldfusion-9

How to get sum of array for specific position?


I have an array:

<cfset fullarray = listtoArray (listofcollumnvalues)>

And it had for example:

fullarray[1]=20
fullarray[2]=11
fullarray[3]=4
fullarray[4]=12.2
etc.

And I wanted to add the sum of the the X position below number: for example if I wanted the sum of the second element and below

2 + 3 + 4= 27.2


Solution

  • ColdFusion 10 introduced the ArraySlice function. It returns an array when you give it an array, a starting location, and an optional length. So ArraySlice(myArray,3,4) would return a "sub-array" with the elements that start at position 3 and includes 4 elements.

    Based on your example:

    mySum = ArraySum(ArraySlice(fullarray,2))
    

    If you're on CF 9 or below, you can use a UDF. At CFLib.org there is

    Warning! arraySlice uses "start" and "end" element arguments, while arraySlice2 uses "start" and "length" arguments, like the built-in CF10 function.