Skip to content

Instantly share code, notes, and snippets.

@stekhn
Last active October 9, 2020 16:58
Show Gist options
  • Save stekhn/e5745746b3d9b872d39dd62508e24122 to your computer and use it in GitHub Desktop.
Save stekhn/e5745746b3d9b872d39dd62508e24122 to your computer and use it in GitHub Desktop.
Calculate the simple moving average (SMA) from an object array
function sma(data, steps = 7, key = 'value') {
return data.map((obj, index) => {
const offset = index - Math.floor(steps / 2);
const window = data.slice(offset, steps + offset);
return Object.assign({}, obj, {
average: window.reduce((sum, curr) => {
return curr[key] ? sum + curr[key] : null;
}, 0) / window.length
});
}).filter(d => d.average);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment