Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda