Using filter to find the odd one out in an array

Using filter to find the odd one out in an array
0

#1

This function is intended to find the even number in an array where all the other numbers are odd, or the odd number in an array where all the other numbers are even.

function findOutlier(integers){
  let oddOne = integers.filter((item) => item % 2 === 1);
  let odderOne = integers.filter((item) => item % 2 === 0)
if (oddOne.length === 1) {
  return oddOne[0];
}
else {
  return odderOne[0];
}
}

It works for most types of arrays, but will sometimes give me ‘undefined’ or if the value at 0 is negative, it will just return that number.
Is there some kind of basic JavaScript rule I’m missing out on? I can’t work out how to get it to work for those ones.


#2

The % operator is the remainder operator in JavaScript and is not the modulus operator as you are thinking it is. In JavaScript when the left operand is negative of the % operator, then the result will be negative.

You could try taking the absolute value of the left operand to see if that works for you.


#3

Great, thank you! Passes all tests now:

function findOutlier(integers){
  let oddOne = integers.filter((item) => Math.abs(item) % 2 === 1);
  let odderOne = integers.filter((item) => Math.abs(item) % 2 === 0);
if (oddOne.length > 1) {
  return odderOne[0];
}
else {
  return oddOne[0];
}
}