I'm currently working on a typescript function that takes in a numeric array (defined as type: number[]
) and computes the mean. I want to make sure that the function can handle cases where the input array includes some null
values. To address this, I introduced an additional parameter that, when set to true
, instructs the function to eliminate any null
s before calculating the mean.
However, I'm struggling to find the right approach for this problem since I am unable to modify the original input array within the function.
This is the code snippet for my calcMean()
function:
function calcMean(arr: number[], nullRemove: boolean = true): number {
if (nullRemove) { // If 'true', which is the default value, remove nulls from the array
const arr: number[] = arr.filter((elem) => elem !== null);
}
// Now proceed with calculating the mean of the modified `arr`
return arr.reduce((acc, v, i, a) => acc + v / a.length, 0); // Reference: https://stackoverflow.com/a/62372003/6105259
}
Upon execution, I encounter the following error message:
Block-scoped variable 'arr' used before its declaration.ts(2448)
I attempted using let
instead of or alongside const
, but unfortunately, it did not resolve the issue.
Can someone guide me on what I might be overlooking here?