Created
June 30, 2021 09:58
-
-
Save codeyourwayup/ee3a2d6f27a103970d289d4f647a483e to your computer and use it in GitHub Desktop.
Mask an array to calculate sub-array average
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 ave(arr) { | |
if (arr && arr.length) { | |
//easy way to get array total is using reduce; c is current | |
const total = arr.reduce((a, c) => { | |
return a + c; | |
}); | |
return total / arr.length; | |
} | |
throw new Error('wrong arr'); | |
}; | |
function calculate(array, win_size) { | |
const result = []; | |
const totalLength = array.length; | |
//always do error checking | |
if (!win_size || win_size > totalLength) { | |
throw new Error('wrong size'); | |
} | |
//cursor at 0; and move downwards to the end; | |
for (let i = 0; i < totalLength; i++) { | |
if ((i) + win_size <= totalLength) { | |
let tempArray = []; | |
for (let j = 0; j < win_size; j++) { | |
console.log(i) | |
tempArray.push(array[i + j]); | |
} | |
//get part of the array and a new one; | |
result.push(ave(tempArray)); | |
}else{ | |
//if cover moves out of the range, stop here! | |
} | |
} | |
return result; | |
} | |
console.log(calculate([2,2,2,1,1,1,1,4,2,3], 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment