Home > OS >  I want to filter only odd negative numbers from an array. Why does n % 2 === 1 not work, but n % 2 !
I want to filter only odd negative numbers from an array. Why does n % 2 === 1 not work, but n % 2 !

Time:11-19

Write a function that returns only negative odd numbers from an array.

const arr = [4, -7, -6]

I first tried:

let negativeOdd = arr.filter(n => n % 2 === 1 && n < 0);
return negativeOdd;

result was an empty array. []. The answer should be [-5].

But when I replaced n % 2 === 1 with n % 2 !== 0, it workded. I am new to JS and was hopeing somenone could help me understand why this is happening. Thank you.

CodePudding user response:

A negative odd number gives n % 2 === -1. Just try it out. In the console, type -5 % 2

CodePudding user response:

The modulo % operator in Javascript divides a number by a divisor (in this case 2), and returns the remainder.

-5 divided by 2 is -2.5, or -2 with a remainder of -1. 2 * -2 -1 = -5

5 divided by 2 is 2.5, or 2 with a remainder of 1. 2 * 2 1 = 5

console.log(-5 % 2);
console.log(5 % 2);

CodePudding user response:

There are different possible definitions of the modulus with respect to negative numbers. For some implementations, it's always true that 0 <= |a % b| < |b|; this is tantamount to always using the floor() function to find the integer quotient before computing the remainder. There are many languages with this interpretation, including Common Lisp and Python. You can get a negative value out of the % operator in these languages, but only if the divisor is negative; the sign of the dividend doesn't change the sign of the result.

In other languages, -|b| < |a % b| < |b|, and the sign of the result does depend on the sign of the dividend. This is equivalent to obtaining the integer quotient by rounding toward zero before taking the remainder; C is in this category (since C99; previous editions of the spec left it up to the implementation). So is Javascript, which is why -1 % 2 is not 1, but -1.

The first definition is often more useful, but easy to define in terms of the second:

const mod = (a,b) => (a % b   b) % b // mod(-1,2) is 1
  • Related