Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

calculate avg count from month in year js

let arr = [
  [ 2020, 1, 2, 1058 ],
  [ 2020, 1, 8, 1055 ],
  [ 2020, 1, 12, 1058 ],
  [ 2020, 1, 23, 1049 ],
  [ 2020, 1, 24, 1050 ],
  [ 2020, 1, 29, 1057 ],
  [ 2020, 2, 1, 1088 ],
  [ 2020, 2, 5, 1087 ],
  [ 2020, 2, 13, 1101 ],
  [ 2020, 2, 26, 1108 ],
  [ 2020, 4, 25, 1119 ],
  [ 2020, 8, 24, 1178 ],
  [ 2020, 8, 25, 1196 ],
  [ 2020, 9, 29, 1214 ],
  [ 2020, 9, 31, 1230 ],
  [ 2020, 10, 20, 1259 ],
  [ 2020, 11, 18, 1276 ]
];
let result = [];
let result2 = arr.reduce((res, [year, month, day, value]) => {
  if (!res[month]) {
    res[month] = { month: month, avg: 0, count: 0, sum: 0 };
    result.push(res[month])//remove this if you are satisfied with the result in result2;
  }
  res[month].sum += value;
  res[month].count +=1;
  res[month].avg = res[month].sum/res[month].count;
  return res;
} , {});
console.log('array of objects {[month, sum, count, avg]}', result);
console.log('object with values {month: {month, sum, count, avg}}', result2);
 Run code snippet
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #calculate #avg #count #month #year #js
ADD COMMENT
Topic
Name
5+3 =