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

203
Views
Is there a way to have the for loop take an array and compute its average?

I have the following code and the logic seems to be correct. However, when I run the last console.log ( 'console.log(bills)'), nothing shows up for its output.

const bills = [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52]

const tipsTotal = [];
let sum = 0;

const calcTip = function(bill) {
  return bill >= 50 && bill <= 300 ? bill * .15 : bill * .20;
}


for (let i = 0; i < bills.length; i++) {
  const value = calcTip(bills[i]);
  calcTip(tipsTotal.push(value));
}

console.log(tipsTotal);

const calcAverage = function(arr) {
  for (let i = 0; arr.length; i++) {

    sum = sum + arr[i];
  }

  let average = sum / arr.length;
  return average;
}

console.log(calcAverage(bills));

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  1. The sum variable should be declared inside calcAverage.
  2. You forgot to check if the loop index reached the end of the array: i < arr.length

const bills = [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52];

const tipsTotal = [];

const calcTip = function(bill) {
  return bill >= 50 && bill <= 300 ? bill * .15 : bill * .20;
}


for (let i = 0; i < bills.length; i++) {
  const value = calcTip(bills[i]);
  calcTip(tipsTotal.push(value));
}

console.log(tipsTotal);

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

  for (let i = 0; i < arr.length; i++) {

    sum = sum + arr[i];
  }

  let average = sum / arr.length;
  return average;
}

console.log(calcAverage(bills));

about 4 years ago · Juan Pablo Isaza Report

0

Reduce works great in these cases

const bills = [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52];
const sum = bills.reduce((sum,bill) => {
  const tip = bill >= 50 && bill <= 300 ? bill * .15 : bill * .20;
  sum += (bill+tip);
  return sum;
},0)

console.log(sum.toFixed(2),(sum/bills.length).toFixed(2));

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!