Skip to main content
March 14, 2025
Question

list of dictionary in forEach with distinct

  • March 14, 2025
  • 2 replies
  • 0 views

Hi Guys,

I have the following values in Appian:

{a!map(year: 2023, value: 15),
a!map(year: 2024, value: 20),
A!map(year: 2023, value: 100)}

and I want to get an output as a map where the values are summed by year.

For example: the years are aggregated and the value is the sum
{a!map(year: 2023, value: 115),
a!map(year: 2024, value: 20)}
thanks

2 replies

yashwantha0914
March 14, 2025

Hi [mention:cdbe3381ad184204981f46f0aec54d80:e9ed411860ed4f2ba0265705b8793d05] 

a!localVariables(
  local!data: {
    a!map(year: 2023, value: 15),
    a!map(year: 2024, value: 20),
    a!map(year: 2024, value: 20),
    a!map(year: 2025, value: 20),
    a!map(year: 2023, value: 100),
    a!map(year: 2023, value: 300)
  },
  local!uniqueYears: union(local!data.year, local!data.year),
  a!forEach(
    items: local!uniqueYears,
    expression: a!map(
      year: fv!item,
      value: sum(
        index(
          index(
            local!data,
            wherecontains(
              tointeger(fv!item),
              tointeger(index(local!data, "year", {}))
            ),
            ""
          ),
          "value",
          {}
        )
      )
    )
  )
)


It works fine, let's see if any others comment more optimized code.

mikes0011
Brainy
March 14, 2025

I'm not a huge fan of optimizing only for the sake of optimizing (often sacrificing quite a bit of readability etc).  The one thing I'd do here is use some loop-internal local variables to help group and abstract the operation of looking up by-year matches, if just for the sake of readability and comprehensibility.  Also as always, I recommend against using index() when what you're really doing is getting a property (and vice versa).  Also, map() data is forgiving enough that you usually don't even have to bother.

a!localVariables(
  local!data: {
    a!map(year: 2023, value: 15),
    a!map(year: 2024, value: 20),
    a!map(year: 2024, value: 20),
    a!map(year: 2025, value: 20),
    a!map(year: 2023, value: 100),
    a!map(year: 2023, value: 300)
  },
  
  local!uniqueYears: union(local!data.year, local!data.year),
  
  a!forEach(
    items: local!uniqueYears,
    expression: a!localVariables(
      local!currentYear: tointeger(fv!item),
      local!itemsForCurrentYear: index(
        local!data,
        wherecontains(local!currentYear, local!data.year)
      ),
      
      a!map(
        year: fv!item,
        value: sum( local!itemsForCurrentYear.value )
      )
    )
  )
)