-4

I have a quote long javascript int array such:

var heights = new Array(120, 123, 145, 130, 131, 139, 164, 164, 165, 88, 89);

I have to calculate the average value three items per time, including the last two numers (88, 89). How can I do a correct loop in order to incluse these last values (which are only two) ?

Ras
  • 628
  • 1
  • 11
  • 29
  • 2
    This sounds more like a *task* than a question. What's the particular problem you have? Please share what you've tried and be specific about the issue you're having. – Jeroen Aug 06 '15 at 12:35
  • Quite simply add a counting variable and check the loop iteration with the array length. If count is equal to 3 OR if iteration is equal to length, perform calculation. – James Donnelly Aug 06 '15 at 12:35
  • could you be any clearer? – Vibhesh Kaul Aug 06 '15 at 12:36
  • 1
    possible duplicate of [Array Sum and Average](http://stackoverflow.com/questions/10359907/array-sum-and-average) – axelduch Aug 06 '15 at 12:37
  • I know how to calculate the average each three values, but my loop is set to exit when an external counter is 3 and then I do the avg. Since the last values are only two, the external counter is 2 so I'm not able to get into. – Ras Aug 06 '15 at 12:52

3 Answers3

0

This is the way to calculate an average for given array from index to index:

var grades = [1,2,3,4,5,6,7,8,9,0];
var average = calculateAverage(grades,0,9);
console.log(average);

function calculateAverage(arr,start,end){
    var total =0;
  for(var i=start; i<=end; i++){
        total+=arr[i];
  }
  var diff = (end-start)+1;
  var avg = total/diff;
    return avg;
}
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
0

Using Rest parameter and for...of loop for an array...

function average(...nums) {
    let total = 0;
    for(const num of nums) {
    total += num;
    }
    let avr = total / arguments.length;
    return avr;
}

console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());

Problem: for no arguments - console.log(average()); - Returns Null where the correct answer must be 0. Any good shorthand solution here?

-2

Thanks to javascript you can perfectly do something like this.

var heights = new Array(120, 123, 145, 130, 131, 139, 164, 164, 165, 88, 89);

var results = [];
for( var i = 0; i < heights.length; i += 3 ){
  results[results.length] = (heights[i] +  (heights[i+1]||0) + (heights[i+2]||0))/Math.min(3,heights.length-i);
}

alert( results.toString() );

heights[i+1]||0 simply means that if heights[i+1] doesn't exist, thus returns null, the whole thing will be equal to 0 (for more information, just google javascript short circuit operators. As many people commented, maybe you didn't do enough research on your task ;)

Robin Nicolet
  • 264
  • 1
  • 7