Bitwise filter function and ODD Number

// Array Filter method
let numbers = [23, 45, 14, 66, 94, 33, 4, 9];
let breakpoint = 30;
let smallNumbers = numbers.filter(function(num){
	return num < breakpoint;
});
let bigNumbers = numbers.filter(checkBig);
function checkBig(num){
	return num > breakpoint;
}

let oddNumbers = numbers.filter(function(num){
	return(num & 1);
});

console.log(smallNumbers);
console.log(bigNumbers);
console.log(oddNumbers);

I am using bitwse system to filter OddNumbers

1 → 00000001
4 → 00001000
5 → 11111011

_____________________________________________

I am surprised that this delivers the result:

let oddNumbers = numbers.filter(function(num){
	return(num & 1);
});

If the number is even than this will return 1 and 0 when ODD → return(num & 1);

So in filter is binary 0 state configured as default true state?

1 Like

No it’s not. When num & 1 is successful you end up with only 1 as the resulting value, which is truthy value.

If you were instead checking for even numbers you would end up with 0, and would need to check that the resulting value equals zero for the desired outcome (that being even values) to be true.

return (num & 0) === 0;
1 Like

Based on whether num is odd or even it will give 0 and 1

But sir that problem finally is delivering odd values.

5 & 1 will give 0
4 & 1 will give 1

Let say for example:
23 & 1 = 1 + 0(last digits of 8 bits binary) = 0 → This will return 0 and this is getting filtered in the final filtered array.
Based on some explanation here.

It looks like there’s some incorrect information there. For example, 5 & 1 is not 0.

In binary, 5 is 0101, and in binary, 1 is 0001
When AND is performed on them, you get a 1 in each column when both values in that column are 1.

0101
0001
----
0001

The resulting value from 5 & 1 is 1.

1 Like

Now I am clear. May be I get some wrong interpretation(I had reached at reciprocal conclusion), but it’s clear now. Binary for even ends in 0 and for odd 1. Thanks for the discussion. so in case of odd:
1+1 = 1, and return will be a true.

Sorry but my brain goes all fuzzy when the plus sign is used there.

It’s the AND operation that is being done (with OR and NOT and XOR being other operations).
So it’s 1 & 1 that equals 1.

1 Like

Yes right, My fault I was using normal mathematical operator.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.