skip to Main Content

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


  1. Try to save all numbers in an array then add them up and divide by the length of array

    let array = [NUMBERS]
    let final = 0
    array.forEach(e => {
      final += e
    });
    final /= array.length
    
    Login or Signup to reply.
  2. 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:

    let sum = 0;
    let total = 0;
    
    const numEl = document.getElementById('num');
    document.getElementById('record').addEventListener('click', () => {
      sum += parseFloat(numEl.value);
      total++;
    });
    
    const output = document.getElementById('output');
    document.getElementById('avg').addEventListener('click', () => {
      output.textContent = sum/total
    });
    Input a value: <input type="number" id="num" /><button id="record">Record</button>
    <br>
    <button id="avg">Calculate average</button>
    <p id="output"></p>

    If you already have an array of values, then use .reduce() to get its sum, then divide by .length:

    const arr = [1, 2, 3, 4, 5]; // example data
    
    const average = arr.reduce((a, x) => a + x)/arr.length;
    console.log(average);
    Login or Signup to reply.
  3. Reduce can do this cleanly.

    const getSumOfArray = (array) => array.reduce((sum, curr) => sum += curr, 0)
    
    const numbers = [1, 2, 3, 4, 5, 6];
    const sum = getSumOfArray(numbers)/numbers.length
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search