Please help me understand the code.
I have this solution I googled, but can’t understand the returned value.
function findOdd(numbers) {
var count = 0;
for(var i = 0; i<numbers.length; i++){
for(var j = 0; j<numbers.length; j++){
if(numbers[i] == numbers[j]){
count++;
}
}
if(count % 2 != 0 ){
return numbers[i];
}
}
};
console.log(findOdd([1,1,1,1,1,1,10,1,1,1,1])); //10
The answer is 10 but I can’t understand the code.
Here is what I know so far, there is a loop inside the loop meaning there is 2 loops happening.
The if statement inside the loop is comparing the elements of the same array.:
if(numbers[i] == numbers[j])
IF:
1 == 1 // true
1 == 1 // true
1 == 1 // true
1 == 1 // true
1 == 1 // true
1 == 1 // true
10 == 10 // true
1 == 1 // true
1 == 1 // true
1 == 1 // true
1 == 1 // true
All is true meaning that count++;
will be 11.
Now this code
if(count % 2 != 0 ){
return numbers[i];
}
if 11 % 2 != 0
or 1 != 0 // true
it is true so it should return numbers[i]
?
What I understand is that it should return [1,1,1,1,1,1,10,1,1,1,1]. because (count % 2 != 0 )
is true .
Please help me understand this. Thank you