What's the easiest way to average an array of integers in javascript? -
if if have multiple arrays such as
[100, 43, 76, 95, 62], [27, 54, 99, 13, 56], [56, 92, 01, 46, 87]
what easiest way 1 array average of of each index? have dynamic number of arrays 6 items in each.
(for example average arrays above [61, 63, 59, 51, 68]
you need 1 loop elements same index of 3 arrays , calculate average:
var arr1 = [100, 43, 76, 95, 62]; var arr2 = [27, 54, 99, 13, 56]; var arr3 = [56, 92, 01, 46, 87]; var res = []; for(var i=0; i<arr1.length; i++){ var avg = math.round((arr1[i]+ arr2[i]+ arr3[i])/3) res.push(avg); } console.log(res);
and if have dymanic number of arrays works charm,
var data = [[100, 43, 76, 95, 62],[27, 54, 99, 13, 56],[56, 92, 01, 46, 87]]; var res = [], sum; for(var i=0; i<data[0].length; i++){ sum = 0; for(var j=0; j<data.length; j++){ sum+= data[j][i]; } res.push(math.round(sum/data.length)); } console.log(res);
Comments
Post a Comment