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

140
Visualizações
Function that returns array with odd numbers and null

I've a task to write function that returns the average value of even numbers from an array. If there are no even numbers in the array, return null. Here are arrays and expected result: [1,2,3,4,5,6,7] - should return "4" and [1,1,1,1] - should return "null". Where shall I put condition for null?I've tried different options but nothing works but maybe my code is wrong.

function getEvenAverage(array) {
    const even = array.filter(function (element) {
        return element % 2 === 0
    });
        const sum = even.reduce(function (sum, element) {
            return (sum + element);
        });
        return sum / even.length;
}
const result1 = getEvenAverage([1,2,3,4,5,6,7])
console.log(result1);
const result2 = getEvenAverage([1,1,1,1])
console.log(result2);

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can achieve this in 1 loop as well:

Logic:

  • Create an object(say map) to hold values
  • Loop on array.
  • Check if current item is even, compute total and length. Set it to map
  • At the end, check for length and return value

function getEvenAverage(array) {
  const map = array.reduce((acc, item) => {
    if (item % 2 === 0) {
      return { total: acc.total + item, length: acc.length + 1 }
    }
    return acc
  }, { total: 0, length: 0 });
  return map.length ? map.total / map.length : null
}
const result1 = getEvenAverage([1, 2, 3, 4, 5, 6, 7])
console.log(result1);
const result2 = getEvenAverage([1, 1, 1, 1])
console.log(result2);

about 4 years ago · Juan Pablo Isaza Relatório

0

check this code

  function getEvenAverage (arr) {
  let temp = [];
  let sum = 0;
  let count = 0;
  arr.map(item => {
    if(item % 2 === 0) {
      temp = [...temp, item]
    }
  })
  temp.map(item => {
    sum += item;
    count +=1;
  })
  if(temp.length ===0) {
    return null
  }
  return sum/count;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to do the following changes:

  1. Add null as an initial value for Array.prototype.reduce
  2. Check if sum === null return sum, otherwise calculate an average value

You can find the code with changed applied below

function getEvenAverage(array) {
    const even = array.filter(function (element) {
        return element % 2 === 0
    });
    const sum = even.reduce(function (sum, element) {
        return (sum + element);
    }, null);
    return sum === null ? sum : sum / even.length;
}

const result1 = getEvenAverage([1,2,3,4,5,6,7])
console.log(result1);
const result2 = getEvenAverage([1,1,1,1])
console.log(result2);

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