Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda