Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - simple exercises

I have a task to write a function getEvenAverage, which should take only one argument - array. This function should return an average value of even numbers from this array. If in the array there aren't any even numbers the function should return null.

I'd really appreciate any feedback :-)

function getEvenAverage(tab) {
  {
    if (i % 2 === 0) {
      for (var i = 0; i < tab.length; i++) {
        sum += parseInt(tab[i], 10);
      }
      var avg = sum / tab.length;
    } else
      console.log('null');
  }
}
like image 486
Anonymous_8712 Avatar asked Sep 21 '26 06:09

Anonymous_8712


2 Answers

You say you need to return something, so return it. Also move your if statement inside your for loop, and fix a few other syntax errors. And as pointed out in the comments, you should divide sum by the number of even numbers to get your avg:

function getEvenAverage(tab) {
  var sum = 0;
  var evens = 0;
  for (var i = 0; i < tab.length; i++) {
    if (i % 2 === 0) {
      sum += parseInt(tab[i], 10);
      evens++;
    } 
  }
  if (evens == 0) {
    console.log("null");
    return null;
  } else {
    var avg = sum / evens;
    return avg;
  }
}

console.log(getEvenAverage([1, 2, 3]));
like image 107
Jack Bashford Avatar answered Sep 23 '26 22:09

Jack Bashford


You could also do it with the array reduce, with a single array traversal

const reducer = (acc, val) => {
  let {
    sum,
    count
  } = acc;
  return (val % 2 === 0 ? {
    sum: sum + val,
    count: count + 1
  } : acc);
};

const getEvenAverage = (input) => {
  const initialValue = {
    sum: 0,
    count: 0
  };
  const output = input.reduce(reducer, initialValue);

  if (output.count === 0) {
    return null;
  } else {
    return output.sum / output.count;
  }
};

console.log(getEvenAverage([1, 2, 3]));
like image 37
Sreekanth Avatar answered Sep 23 '26 22:09

Sreekanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!