Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!