arrays - Calculating quarterly and yearly avarage through javascript -


i have array:

const test = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]; 

i want group elements of array chunks of size 3 (quarters) , size 12 (years):

const quarters = [[1,2,2],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18],[19,20]]; const years = [[1,2,2,4,5,6,7,8,9,10,11,12],[13,14,15,16,17,18,19,20]]; 

i want compute sum of each chunk:

const quartersums = [5,15,24,33,42,51,39]; const yearsums = [77,132]; 

how do so?

if want group elements chunks of size n then:

const groupinto = (n, xs) => xs.reduce((xss, x, i) => {      if (i % n === 0) xss.push([]); // create new group      xss[xss.length - 1].push(x);   // push in last group      return xss;  }, []);    const xs = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];    const quarters = groupinto(3,  xs);  const years    = groupinto(12, xs);    console.log(json.stringify(quarters));  console.log(json.stringify(years));

on other hand, if want find sum of these chunks:

const suminto = (n, xs) => xs.reduce((ys, x, i) => {      if (i % n === 0) ys.push(0);      ys[ys.length - 1] += x;      return ys;  }, []);    const xs = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];    const quarters = suminto(3,  xs);  const years    = suminto(12, xs);    console.log(json.stringify(quarters));  console.log(json.stringify(years));

hope helps.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -