# How to iterate the list value one by one and add the previously stored value

Hi, I have list like this

``````[%{"date" => "30-04-2021", "minimumAmount" => "10000"}, %{"date" => "30-07-2021", "minimumAmount" => "10000"}, %{"date" => "30-011-2021", "minimumAmount" => "5000"}]
``````

From this i have to iterate each map and minimumAmount value should get added to previous minimumAmount value. How can i achieve this like below?

[%{“date” => “30-04-2021”, “minimumAmount” => “10000”}, %{“date” => “30-07-2021”, “minimumAmount” => “20000”}, %{“date” => “30-011-2021”, “minimumAmount” => “25000”}]

Thank You

You need to iterate the list and pass the previous sum.

Enum.reduce, or simple recursion should do it.

For example using an acc like {[], 0}

You also need to parse string to integer in the process…

My question is the same. How can i store the previous sum value as another variable, to add it to newly coming value.

The 0 is the previous sum value in the acc.

It would look like this…

``````{list, _} = Enum.reduce(list, {[], 0}, fn %{"minimumAmount" => ma_str} = x, {l, sum} ->
new_sum = sum + String.to_integer(ma_str)
{[%{x | "minimumAmount" => to_string(new_sum)} | l], new_sum}
end)
``````

At the end, You might want to reverse the list.

1 Like

As @kokolegorille have said, you can reduce the list using an accumulator

Enum.reduce(your_list, 0, fn x, acc → acc + String.to_integer(x[“minimumAmount”]) end)

1 Like

You probably need to pass a list as well in the acc, because it is the return value.