Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Tadjiev Codes
Tadjiev Codes
9,626 Points

Can someone explain why I can't get the average number from the array?

```1.Declaring an array with number let numberArrays = [10, 58, 47, 12, 5, 4, 8, -7, 521, -99]; let totalNumber = 10 + 58 + 47 + 12 + 5 + 4 + 8 + -7 + 521 + 99; //2.Print the array and its length. outputElement.innerHTML += numberArrays.length;

    //3.Find and output the average of the array.

    function findAverage(a, b) {
        //totalNumber = a;
        return a / b;
    }
    var averageNum = findAverage(totalNumber, numberArrays.length);
    outputElement.innerHTML += Math.round(averageNum);
The normal function 

function findAverage(a, b) { //totalNumber = a; return a / b; } ``` although works if i replace it with numbers. Thanks)))

1 Answer

It looks like for totalNumber you have 99 instead of -99. I added the following to compare sums:

let numberArrays = [10, 58, 47, 12, 5, 4, 8, -7, 521, -99];
let totalNumber = 10 + 58 + 47 + 12 + 5 + 4 + 8 + -7 + 521 + -99; 

console.log(totalNumber)
console.log(numberArrays.reduce((a, b) => a + b, 0))
Tadjiev Codes
Tadjiev Codes
9,626 Points

Thanks) YEs I missed that - 99 . But your code compares it though doesn't output the average number? Thanks in advance)

Tadjiev Codes
Tadjiev Codes
9,626 Points
var Numbers = [10, 58, 47, 12, 5, 4, 8, -7, 521, -99];


        function printValueWNote(string, value) {

            averageDisplay.innerHTML += string + " : " + value + "<br>";
        }

        function averageOfArray(array) {
            var average = 0;
            var sum = 0;
            for (var index = 0; index < array.length; index++) {
                sum += array[index];
            }
            average = sum / array.length;
            return average;
        }


        printValueWNote("Average", averageOfArray(Numbers));
        printValueWNote("Maximum", Math.max.apply(null, Numbers));
        printValueWNote("Minimum", Math.min.apply(null, Numbers));

I came up with another solution so it generates the average number, max and min numbers from this array. I assume I could do this without the function parameter array I used instead use the totalNumber variable from last code and divide it to the numberArrays.length I mean divide it to the length of the arrays.