celllaa95 - 1 year ago 57
Javascript Question

# How many Odd and Even number are the in a array

I have created an Array with some numbers.
I want to find out how many even, and how many odd numbers it is in
this Array. I have to print it out like this: (this is just an example)

Even number: 6

Odd number: 7

I need to make a loop that count up how many it is off even and odd numbers.

This is what I have so far

``````<script>

var tall = [5,10,15,20,25,30,35,40,45,50];

function run() {

tall = [5,10,15,20,25,30,35,40,45,50];

liste(tall);

}

function liste(arr) {

var sumOdd = 0; // Odd 1, 3, 5 etc..
var sumPar = 0; // Even 2, 4, 6 etc..

for(var i = 0; i < arr.length; i++) {
if(arr[i] % 2 === 0) {
sumPar += arr.length;
}
else {
sumOdd += arr.length;
}                                            // Even numbers                     // Odd numbers
document.getElementById("print").innerHTML = "Partall:  " + sumPar + "<br />" + "Oddetall:  " + sumOdd;

}

}
}
</script>
``````

Its something that is wrong here, and I dont know what.

You were adding `arr.length` which is the array length. Instead you should simply increment the number

``````var tall = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50];

liste(tall);

function liste(arr) {
var sumOdd = 0;
var sumPar = 0;

for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
sumPar++;
} else {
sumOdd++;
}
}

console.log("Odd : " + sumOdd);
console.log("Par : " + sumPar);
}``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download