Would like to convert my current Angular reduce
function below to calculate a moving average based on a period of every ~2-3 items. Is this possible to do w/ a standard Angular Reduce function?
This is what I currently have to compute a basic average, but would like to convert it to a moving average w/ a settable period if possible, but not sure how/if it’s possible to do w/ a standard Angular JS Reduce function.
const data = [
{ val: 20 },
{ val: 15 },
{ val: 10 },
{ val: 12 },
{ val: 15 },
{ val: 09 },
{ val: 14 },
{ val: 17 },
{ val: 11 },
{ val: 15 }
]
var avg = data.reduce((accum, curVal) => accum + curVal.val, 0) / data.length;
console.log("avg= " + avg);
2
Answers
You can use the slice function to get a portion of the array
If I’ve understood the question correctly you want an array with a set of averages based on a window that moves one entry at a time across the data. Here’s an example using a for loop, please see the comments for how this works:
Same idea but with a reduce function: