I would like to create a dynamic calculator with several amount of input items (user decides)
Let say, I want to sum all the input numbers up and then divide by amount of all inputs that took part in calculating.
How can I do it?
I tried to find sth on YouTube and another posts but unfortunately didnt found. 🙁
3
Answers
Try to save all numbers in an array then add them up and divide by the length of array
Try keeping a running sum that gets added to and a running total that gets incremented each time. Then, all you need to do is calculate
sum/total
, rather than the overhead of getting the sum of an array of values each time:If you already have an array of values, then use
.reduce()
to get its sum, then divide by.length
:Reduce can do this cleanly.