dimanche 26 juillet 2020

A better way to write this recursive function that finds an odd amount of numbers in an array

I made this recursive solution to find if a number is in an array an odd amount of times and if not return null. I was wondering if anyone had any suggestions for better cleaner code. Just trying to improve, Thanks!

let odd = [0, 5, 6, 6, 4, 0, 1, 5, 2, 4];
let j = 1;
let number;

function tryAgain(odd) {
  let counter = 0;

  odd.forEach((num, i, arr) => {
    if (num === arr[j]) {
      counter++;
      number = arr[j];
    }
  });
  if (counter > 1 && counter % 2 !== 0) {
    return number;
  } else {
    j++;
    if (j > odd.length) {
      number = null;
      return false;
    } else {
      tryAgain(odd);
    }
  }
  return number;
}

Aucun commentaire:

Enregistrer un commentaire