function findOdd(A) {
var odd = 0;
A.forEach(num => {
A.forEach(num2 => {
if (num == num2) {
odd = odd + 1;
};
});
if (odd % 2 == 1) {
console.log("num = " + num);
return num;
}
odd = 0;
});
}
var result = findOdd([5, 0, 0, 0, 2, 2, 3, 3, 4, 4]);
console.log(result);
When I try to return num, it is returning as undefined. And if I remove the "return" statement it is printing correctly to the console.
forEachignores its callback'sreturnvalue.Array.prototype.forEachiterates over every array item unconditionally, you cannot stop mid-way. In this case there is no reason to not use a good oldforloop.forEachit ignoresreturnvalue as well as inforloop thereturnstatement breaks the loop once it is executed. Therefore consider putting thereturnstatement outside the for loop.