0
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.

4
  • 7
    forEach ignores its callback's return value. Array.prototype.forEach iterates over every array item unconditionally, you cannot stop mid-way. In this case there is no reason to not use a good old for loop. Commented Jul 21, 2020 at 3:26
  • 1
    With the return the final assignment of “odd = 0” is skipped in some cases which also affects the behavior of subsequent code. Commented Jul 21, 2020 at 3:28
  • Are you just trying to filter the odd numbers from your array, or something more? Commented Jul 21, 2020 at 3:32
  • In forEach it ignores return value as well as in for loop the return statement breaks the loop once it is executed. Therefore consider putting the return statement outside the for loop. Commented Jul 21, 2020 at 4:41

1 Answer 1

1

You can't break out of forEach using return and return it. You are not returning anything from your function as return from foreach does not get returned.

You can use for loop to do this.

function findOdd(A) {
  var odd = 0;

  for (let i = 0; i < A.length; i++) {
    for (let j = 0; j < A.length; j++) {
      if (A[i] == A[j]) {
        odd = odd + 1;
      }
    }

    if (odd % 2 == 1) {
      console.log("num = " + A[i]);
      return A[i];
    }
    odd = 0;
  }

}

var result = findOdd([5, 0, 0, 0, 2, 2, 3, 3, 4, 4]);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.