Looping through an array and summarizing properties

repost from discord

hey guy hoping someone could help a coding noob such as myself figure this one out. I have and array of “ingredients”, each “ingredient” is itself any array with macronutrient values. id like to be able to loop through the array and add each macronutrient together for a total displayed at the bottom of my screen. any help would be greatly appreciated/hope i explained correctly.

Would something like this help.

The code in the function is:

var result = 0

for(var item of Inputs.Items) {
    result += parseFloat(item.Protein)

Outputs.Result = result

One tricky thing is that your values are actually strings (you can see that since they are listed in " " in the inspector). So you need the parseFloat function to convert them to numbers so you can add them up. (otherwise, the += would just concatenate the strings)


Thank you so much!

would you be able to show me what the code would be if they were numbers?
its some thing i should change anyway.

thanks again

Same code, just remove the parseFloat(item.Protein) and replace with just item.Protein

1 Like