Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

When you split a string from user input you get an array of strings. Thus you have to parse these strings into numbers and filter out any non numeric values before calculation.

function test() {
  const inputValue = document.getElementById("input").value;
  var values = inputValue.split(',').map(v => parseFloat(v)).filter(v => !Number.isNaN(v));

  const avg = values.reduce((a, b) => a + b, 0) / values.length;

  document.getElementById("lbl").innerHTML = (!Number.isNaN(avg)) ? avg : '';
}

setInterval(test, 100);
<textarea id="input"></textarea><br>
<label id="lbl">Result Here</label>
<textarea id="txt"></textarea>

about 4 years ago · Juan Pablo Isaza Report

0

// 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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!