Matt Beagle
Matt Beagle

Reputation: 49

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));

Upvotes: 1

Views: 45

Answers (2)

mplungjan
mplungjan

Reputation: 178285

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));

Upvotes: 2

kol
kol

Reputation: 28708

  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));

Upvotes: 2

Related Questions