Search code examples
javascriptarraysaverage

Javascript Convert Textarea input to Array to calculate average total


I am trying to get the script to calculate the average from numbers entered into a text area. The numbers are seperated by a comma

I either get a NaN value or it just doesnt work right.

This code came closest to actually working. However it only adds the comma as a new element and all numbers are just combined in the first element, dividing the number by the amount of comma's.

document.querySelector("#input").addEventListener("input", function test() {
  const strng = document.getElementById("input").value;
  var arr = strng.split(',');

  const avg = arr.reduce((a, b) => a + b, 0) / arr.length;
  document.getElementById("lbl").innerHTML = avg;
});


function cycle() {
  var area = document.getElementById("txt").value;
  var lines = area.split(',');

  const average = arr => arr.reduce((a, b) => a + b, 0) / arr.length;

  document.getElementById("lbl").innerHTML = average([lines]).toFixed(2);

}
setInterval(cycle, 100)
<textarea id="input"></textarea>
<label id="lbl">Result Here</label>
<textarea id="txt"></textarea>

The cycle() function gave me a NaN value right after entering the first comma in the textarea.

Can someone help me out?


Solution

  • // access the DOM elements
    const inpTxt = document.getElementById("input");
    const outTxt = document.getElementById("lbl");
    
    // add event listener to text-area "input" event
    inpTxt.addEventListener("input", () => {
      // collect the list of comma separated numbers into an array "numList"
      const numList = inpTxt
        .value                    // access the DOM element "inpTxt"'s value attribute
        .split(',')               // ".split()" using "comma" as the seperator
        .map(Number)              // convert each element into a number
        .filter(                  // sanity check to remove any non-number data
          x => !isNaN(x)
        );
      console.log(numList);       // to see in real-time the "numList" array on console
      if (numList.length) {       // if there are any valid numbers in the array
        outTxt.innerText = (      // change the "label"'s innerText
          numList.reduce(         // sum the numbers in the "numList" array
            (total, num) => total + num,
            0                     // initialize the "sum" to zero
          ) /                     // divide into "numList.length" to compute average
          numList.length
        );
      }
    });
    <div>
      Type comma-separated numbers in below input box
      and average will be calculated
    </div>
    <div><textarea id="input"></textarea></div>
    <div><label id="lbl">Result Here</label></div>