How do I create a sum within an aura:iteration?

<aura:attribute name="sum" type="Integer"/>

<aura:iteration items="[0,0,0,1,0,0,0,0,0,0]" var="item">
    do something with {!item}
    <aura:set attribute="sum" value="{!v.sum + item}"/>

<aura:set attribute="sum" won't work as figured out here

  • Is there any other way to change attributes within the markup?
  • Should I throw events to sum it up with java script?
  • Is it even considered good practice to do it within the markup?
  • Or should I prepare the data before initializing the component?
  • for counter you can use attribute indexVar="counter" of aura:iteration and use it as {!counter} within interation. – Animesh Jul 25 '17 at 9:45
  • @Animesh I'm more trying to use a calculated value after finishing the iteration to display the sum ect. I will remove the counter since it might be irritating. – Basti Jul 25 '17 at 9:55
  • then create an attribute of type Integer[] and initialise it during init. – Animesh Jul 25 '17 at 10:06

You cannot dynamically calculate the value of sum via markup expression in Lightning Component. You need to calculate the value in the controller.js and store in a separate attribute in the component during the initialization.


<aura:attribute name="values" type="List" default="[0,0,1,0,0,1]" />
<aura:attribute name="sum" type="Interger" />

<aura:handler name="init" value="{!this}" action="{!c.initHandler}" />



    initHandler : function(cmp) {
       var values = cmp.get("v.values");
       var total = values.reduce(function(sum, value) {
          return sum + value;
       cmp.set("v.sum", total);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.