Find The One Element In An Array That is Different From The Others https://www.codewars.com/kata/find-the-stray-number/train/javascript

I solved this challenge by sorting from least to greatest, and checking if the first element in the array matched the second element in the array. 

If the first element does not match, then the different element is the first element. 

If the first element does match, then the different element is the last element.

function stray(numbers) {
  numbers = numbers.sort((a, b) =&gt; a - b);
  if (numbers[0] !== numbers[1]) {
    return numbers[0];
  }
  else {
    return numbers[numbers.length - 1];
  }
}
console.log(stray([17, 17, 3, 17, 17, 17, 17]));


I'm wondering if / how this can be done with the filter() method instead?
This is a similar idea to the other answers here, but the implementation is a bit different.

First of all, we can assume that the array's length is at least 3, since it needs to have at least two of the same values and one different value.

Let's start by handling the case where the stray value is not in the first element. We could simply write:

a.find(v =&gt; v != a[0])


That is, find an element that's different from the first element. But what if the stray element comes first in the array? We can check if the first two elements differ. If they do, then the stray is either in the first or second position, so the third element is not a stray. In this case, we can check against the third element instead of the first; otherwise we check against the first element as before, thus:

a.find(v =&gt; a[0] != a[1] ? v != a[2] : v != a[0])


This is a bit code-golfey and not very readable, so I wouldn't recommend it in production, but it may be of some interest as a curiosity.

It may be worth noting that this solution appears to perform quite well, and can be further optimized by doing the inequality check on the first two elements before invoking find, and by using the third parameter to find to access the array, making the callback a pure function and eliminating the need to reference the array via the closed-over variable, for example:

a.find(a[0] != a[1] ?
    (v, i, a) =&gt; v != a[2] :
    (v, i, a) =&gt; v != a[0])