javascript - Iterate over array and calculate average values of array-parts -
i have array this:
["2011-06-16 16:37:20",23.2], ["2011-06-21 16:37:20",35.6], ["2011-06-26 16:37:20",41.8], ["2011-07-01 16:37:20",25], ["2011-07-06 16:37:20",22.8], ["2011-07-11 16:37:20",36.4], ["2011-07-16 16:37:20",34], ["2011-07-21 16:37:20",20] [...] format: [$date,count]
now need add 3rd 4th value every array element, average of n counts before or after.
example if n=3
the 3rd value should average of 3 count-values before , 4th value should average of 3 count-values after current array element. result that:
["2011-06-16 16:37:20",23.2, null, 34.13], ["2011-06-21 16:37:20",35.6, null, 29.86], ["2011-06-26 16:37:20",41.8, null, 28.06], ["2011-07-01 16:37:20",25, 33.53, 31.06], ["2011-07-06 16:37:20",22.8, 34.13, 30.13], ["2011-07-11 16:37:20",36.4, 29.86, null], ["2011-07-16 16:37:20",34, 28.06, null], ["2011-07-21 16:37:20",20, 31,06, null]
the null
value nothing more placeholder values cant calculated, because there not enough values calculate average of n counts. it's possible place average of available counts, "24.4
"(23.2+35.6)/2 3rd line instead of null
:
["2011-06-26 16:37:20",41.8, 24.4, 28.06],
i have no idea, ho build code that.
hope hint or assistance.
thank you.
//update: sorry, but..please: explain me, why 2 people votes question down? don't know why. that's not fair - talk me, if did mistake? sorry that!
a solution using various higher-order functions:
var arrs = [ ["2011-06-16 16:37:20",23.2], ["2011-06-21 16:37:20",35.6], ["2011-06-26 16:37:20",41.8], ["2011-07-01 16:37:20",25], ["2011-07-06 16:37:20",22.8], ["2011-07-11 16:37:20",36.4], ["2011-07-16 16:37:20",34], ["2011-07-21 16:37:20",20]]; function avg(arr) { return (arr.reduce(function(acc, el, i) { return el + acc; }, 0) / arr.length).tofixed(2) * 1; } function visit(acc, el, i, arr) { el.push((acc.length >= 3) ? avg(acc) : null); acc[i % 3] = el[1]; return acc; } arrs.reduce(visit, []); arrs.reverse().reduce(visit, []); arrs.reverse();
result:
[["2011-06-16 16:37:20", 23.2, null, 34.13], ["2011-06-21 16:37:20", 35.6, null, 29.87], ["2011-06-26 16:37:20", 41.8, null, 28.07], ["2011-07-01 16:37:20", 25, 33.53, 31.07], ["2011-07-06 16:37:20", 22.8, 34.13, 30.13], ["2011-07-11 16:37:20", 36.4, 29.87, null], ["2011-07-16 16:37:20", 34, 28.07, null], ["2011-07-21 16:37:20", 20, 31.07, null]]
Comments
Post a Comment