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

99
Vistas
Filter method in a function to output an average

I am trying to filter through a given array and only output the average of a new array's numbers. However, for some reason, the length of an array is based on the original array's length where other data types are located, although I specified the length to be based on a newArr array.

Could someone please help?

const bills = [[], 4, 42, 9, "error"];

const calcAverage = function (arr) {
    let sum = 0;
    let avg;
    for (let i = 0; i < arr.length; i++) {
        if (typeof arr[i] === "number") {
            sum = sum + arr[i];
            avg = sum / arr.length
        } else {
            const newArr = arr.filter(arr => typeof arr[i] === "number");

            for (let b = 0; b < newArr.length; b++) {
                sum = sum + newArr[b];
                avg = sum / newArr.length;
            }
        }
    }
    return avg;
}


console.log(calcAverage(bills));

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You don't really need to use .filter with the for loop.

Instead you can keep a count of the amount of numbers encountered so far and use that to calculate your average. If you come across an item that isn't a number we can just skip it and move on.

const bills = [[], 4, 42, 9, 'error'];

const calcAverage = function (arr) {
  let sum = 0, avg = 0;

  for (let i = 0, count = 0; i < arr.length; i++) {
    if (typeof arr[i] === 'number') {
      count++;
      sum += arr[i];
      avg = sum / count;
    }
  }

  return avg;
};

console.log(calcAverage(bills));

about 4 years ago · Juan Pablo Isaza Denunciar

0

revised:

const bills = [[], 4, 42, 9, "error"];
const calcAverageOLD = function(arr) {
  let sum = 0;
  let avg;
// filter Before loop for correct length
  const newArr = arr.filter(primitive => typeof(primitive) === "number");
  console.log(newArr)
  for (let i = 0; i < newArr.length; i++) {
      sum += newArr[i];
      avg = sum / newArr.length;
    }
      return avg;
  }
console.log('old', calcAverageOLD(bills))
about 4 years ago · Juan Pablo Isaza Denunciar

0

Are you trying to calculate the average from the numbers in the array?

I am not sure if I understand your question but here is what I did: First filter the numbers and then it's much easier to calculate the average

const bills = [[], 4, 42, 9, "error"];
const calcAvarage2 = function (arr){
    let newArr = arr.filter( item=>typeof(item)==="number")
    let sum = 0;
    for( number of newArr){
        sum += number;
    }
    let avg = sum/ newArr.length

    return avg
}

console.log(calcAvarage2(bills));
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