How to innerHTML a function with array as parameter?

869 Views Asked by At

I am learning about looping thorugh arrays - I want to pass the result of an if else statement in the forEach function (inside another function with array as parameter) to HTML using innerHTML (does not have to be innerHTML if you know better methods I do not mind). It checks if number are even and should return true and false. My result is undefined, but in console.log I can see that the loop is working. At the bottom I left "What in here" as I do not know how to select it properly.

Any help is welcome, including rebuilding the code.

var myArray = function (nums) {

    var average = 0;
    var totalSum = 0;

    nums.forEach(function (value) {
        //returns total sum
        totalSum = totalSum + value;

        //return average
        average = totalSum / nums.length;

        //return true if at least one even if not false
        if (value % 2 === 0) {
            console.log(value + " true");
            return true;
        } else {
            console.log(value + " false");
            return false;
        };

    })

    console.log("Total sum: " + totalSum);
    console.log("Average: " + average);
    console.log("Max number: " + Math.max.apply(null, nums));
    //document.getElementById("array").innerHTML = /*What in here?!*/
};


myArray([1, 1, 1, 2])
2

There are 2 best solutions below

6
On BEST ANSWER

Just take a variable for the occurrence of even or odd numbers.

var myArray = function (nums) {
    var average = 0;
    var totalSum = 0;
    var hasEven = false; // flag if at least one value is even => true, otherwise false
    nums.forEach(function (value) {
        totalSum = totalSum + value;
        hasEven = hasEven || !(value % 2);
    });
    average = totalSum / nums.length; // just call it once
    console.log("Total sum: " + totalSum);
    console.log("Average: " + average);
    console.log("Max number: " + Math.max.apply(null, nums));
    console.log("Contains at least one even value: " + hasEven);
};
myArray([1, 1, 1, 2]);
1
On

An easy way would be to use JSON.Stringify

document.getElementById("array").innerHTML = JSON.Stringify(nums);