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

205
Visualizações
How do I merge these two functions that are performing the same thing to different variables?

I need help in merging these two function that are performing the same action of adding all the elements in a list

function totalSpendings() {
  let totalSpending = 0;
  if (this.spendingList.length > 0) {
    totalSpending = this.spendingList.reduce(function (
      totalValue,
      curentValue
    ) {
      totalValue += curentValue.inputSpending;
      return totalValue;
    },
    0);
  }
  this.spending_summary.textContent = totalSpending;
  return totalSpending;
}

function totalEarnings() {
  let totalEarning = 0;
  if (this.earningList.length > 0) {
    totalEarning = this.earningList.reduce(function (totalValue, curentValue) {
      totalValue += curentValue.inputEarning;
      return totalValue;
    }, 0);
  }
  this.earning_summary.textContent = totalEarning;
  return totalEarning;
}

I tried out this way to create a common function but was unsuccessful :

    total(arg1,arg2,arg3){

let total = 0;
    if (arg1.length > 0) {
        total = arg1.reduce(function (totalValue, curentValue) {
            totalValue += arg3;
            return totalValue;
        }, 0);

    }
    arg2.textContent = total
    return total;

}

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

0

You could try to implement a callback function, e.g.

const spending_summary = {};
const earning_summary = {};
const spendingList = [
  {inputSpending: 1},
  {inputSpending: 2},
];
const earningList = [
  { inputEarning: 1},
  { inputEarning: 2},
];

function total(list, reducer) {
  if (list && list.length > 0) {
    return list.reduce(reducer, 0);
  }
  return 0;
}

spending_summary.textContent = total(spendingList, (total, current) => total += current.inputSpending);
earning_summary.textContent = total(earningList, (total, current) => total += current.inputEarning);

console.log(spending_summary);
console.log(earning_summary);

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