Search code examples
listcoldfusionlucee

Sum up dynamic fields in list


I have a list like:

<cfset list ="group 1:1; group 2:4; group a:7; group 1:3; group a:1;">

What I want to do is count (sum up) how many people are in group 1, group 2, group a, etc.. Now these fields are dynamic, so I don't know the exact name of the groups.

So the end result in this example is:

group 1: 4
group 2: 4
group a: 8

So the list is just an example, in reality it's much bigger with more groups (dynamic names). I'm using Coldfusion/Lucee. Can someone help me with this?


Solution

  • Just one of numerous of possible alternative ways of doing this. Starting from using a query instead of a list as the starting value.

    What I am doing is to loop the list with ; as delimiter and adding the values to a structure. I later use that structure to loop and list the final total.

    <cfset list ="group 1:1; group 2:4; group a:7; group 1:3; group a:1;">
    <cfset totalStruct = {}>
    <cfloop list="#list#" item="group" delimiters=';'>
      <cfset groupName = listFirst(group, ':')>
      <cfset groupNameKey = replace(groupName, ' ', '', 'all')>
      <cfset groupValue = val(listLast(group, ':'))>
      <cfif !structKeyExists(totalStruct, groupNameKey)>
        <cfset totalStruct[groupNameKey] = {name:groupName, total=groupValue}>
      <cfelse>
        <cfset totalStruct[groupNameKey].total += groupValue>
      </cfif>
    </cfloop>
    <cfoutput>
      <ul>
        <cfloop collection="#totalStruct#" item="group">
          <li>#totalStruct[group].name# : #totalStruct[group].total#</li>
        </cfloop>
      </ul>
    </cfoutput>
    

    DEMO