Sum won't add from array

so, i was make a block for my extension which is the “average of array” block but when i tried to add up the sum it returns NaN. Here’s the code:

     //% block="Find the average of $array"
    export function AverageOf(array: number[]) {
        let sum: 0
        for (let i = 1; i < array.length; i++) {
            sum += array[i];
            console.log(sum)
        }
        return sum;
    }
1 Like
let sum: number = 0

If you want the average, then you want

return sum / array.length

Also, the first index for arrays is zero (0), not one (1).

2 Likes

You wrote

let sum: 0

Instead of:

let sum: number
or
let sum: number = 0

Also there are three other bugs I’m pretty sure in your block:

  1. Missing Division: You are only adding the numbers, not dividing by the array length to get an actual average.
  2. Skipping the First Element: Your loop starts at let i = 1. JavaScript arrays start at 0, so you are completely skipping the first item in the list.
  3. Empty Arrays: If an empty array is passed, dividing by a length of 0 will return NaN. [1]

I fixed your code so it gets the average of an array.

//% block="Find the average of $array"
export function AverageOf(array: number[]): number {
    if (array.length === 0) return 0; // Handle empty array case

    let sum = 0; // Correctly initializes value to 0
    for (let i = 0; i < array.length; i++) { // Starts at index 0
        sum += array[i];
    }
    
    return sum / array.length; // Correctly calculates the average
}
3 Likes

Thank you for helping!

1 Like

You also can write the for loop without using the index:

    for (let element of a) {
        sum += element
    }

If you want to be really fancy, you can eliminate the loop and use the forEach() method on the array instead.

    a.forEach((element: number) => sum += element)
3 Likes