Even occurring element in an array

in code


This solution employs the previous solution. With the XOR method explained, you invert the array:

  1. Find the unique elements in the array.
  2. Concat the new array to the original. This makes the even (even count) numbers odd, and the odd numbers even.
  3. Use the XOR method as before.

Behold:

function evenOccurring(array) {
    return [].concat(array, array.filter(unique)).reduce(xor);
}

function unique(element, index, array) {
    return array.indexOf(element) === index;
}

function xor(previous, current) {
    return previous ^ current;
}

How does the filter work? indexOf returns the first index where the value is found. So in [0, 1, 0, 1]:

arr.indexOf(0) === 0 // expected index: 0 (true)
arr.indexOf(1) === 1 // expected index: 1 (true)
arr.indexOf(0) === 2 // expected index: 0 (false)
arr.indexOf(1) === 3 // expected index: 0 (false)

Therefore only unique elements are returned. AFAIK this is a slow way to filter for unique elements, but it works. :D

To test:

let a = [0, 1, 2, 0, 1, 2, 0, 1, 2, 2];
evenOccurring(a); // 2


A Summer of Running

in running

Achill Half Marathon

in running


Your email address will not be published. Required fields are marked *