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.
{a!map(year: 2023, value: 115), a!map(year: 2024, value: 20)}
Discussion posts and replies are publicly visible
Hi cugino95
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", {} ) ) ) ) )
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 ) ) ) ) )