Last active
October 9, 2020 16:58
-
-
Save stekhn/e5745746b3d9b872d39dd62508e24122 to your computer and use it in GitHub Desktop.
Calculate the simple moving average (SMA) from an object array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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