Find the odd integer (js fundamentals) - logic

The task Given an array of integers, find the one that appears an odd number of times.

There will always be only one integer that appears an odd number of times.

Examples [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd). [1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).

I saw this solution but I struggle to understand the logic why it works:

e.g.

function findOdd(arr) {
  return arr.find((item) => arr.filter(el => el == item).length % 2)
}


console.log(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])) // returns 5

If the number must be odd, why it isn't ... .length % 2 !== 0; I'd really appreciate any help! Thanks :)


Solution 1:

arr.filter(el => el == item).length % 2 returns 0 or 1. This is good enough, as that value will be coerced to boolean, and since 0 is falsy and 1 truthy, it has the intended effect.

Note that this algorithm has a O(n²) complexity. It is possible to do this more efficiently.

function findOdd(arr) {
  return arr.reduce((a, b) => a ^ b);
}

console.log(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])) // returns 5

This uses XOR. All values in the array are XOR'd together. It is based on the consideration that a ^ a == 0 for any value of a. And a ^ 0 == a. So if we have an odd number of a, we will get a, otherwise 0. As there is only one number whose occurrence is odd, we will find it this way. The special case of 0 will also work.