2

I would like to filter an array containing zeros (0) whilst capturing them too:

var arr1 = [-200, -163, -26, -4, 0, 7, 76];

var evens = arr1.filter(function(x) {
  if (x % 2 === 0 || x === 0) {
    return x;
  }
})

console.log(evens);

Why do I NOT get zero back in my evens array? If zero is not classed as even, shouldn't my:

|| x === 0

statement catch the zero?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
newcasio
  • 243
  • 1
  • 6
  • 14
  • 3
    This is not how [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) works. The callback needs to return a boolean. – Jeto Aug 16 '18 at 11:49
  • 1
    You want to return true rather than x – eddiewould Aug 16 '18 at 11:49
  • Possible duplicate of [Understanding JavaScript Truthy and Falsy](https://stackoverflow.com/questions/35642809/understanding-javascript-truthy-and-falsy) – str Aug 16 '18 at 11:50

6 Answers6

8

You need to return true or false from the Array#filter function. Based on the return value it will populate the returned array. Because conditions return boolean, you can just set the return value to the condition.

var arr1 = [-200, -163, -26, -4, 0, 7, 76];

var evens = arr1.filter(function(x) {
   return x % 2 === 0;
})

console.log(evens);

Even more shorter syntax with arrow function

var arr1 = [-200, -163, -26, -4, 0, 7, 76];

var evens = arr1.filter(x => x % 2 === 0);

console.log(evens);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
3

Return true/false from inside of filter:

var arr1= [-200,-163, -26, -4, 0, 7,76];

var evens = arr1.filter(function(x){
  return x%2 === 0 || x === 0
})

console.log(evens);

In your code when you return 0, filter will consider it "falsy" and hence you don't get 0 inside your filtered Array.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
1

Because 0 is considered a "falsy" value.

Your filter function is essentially returning false for 0 and filtering it from the array.

Check this out for a deeper look.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
NarutoBruto
  • 103
  • 11
0

Array filter expects return as boolean value not number
If you need value in result it should be true else false;
0 is considered a false value.

you can return true in your function

var arr1 = [-200, -163, -26, -4, 0, 7, 76];

var evens = arr1.filter(function(x) {
  if (x % 2 === 0 || x === 0) {
    return true;
  }
})

console.log(evens);
Rupesh Agrawal
  • 645
  • 8
  • 22
0

const myEvennessFilter = (args) => args.filter(elem => (elem % 2) === 0);
console.log(myEvennessFilter([1,2,3,4,5,6,7,8,9]));
0

To make it Run Up to 25% Faster, replace elem % 2 == 0 with (elem & 1) === 0:

// how to filter out even numbers using filter() in js
let numbers = [1,2,3,4,5,6,7];
let even_numbers = numbers.filter(elem => elem%2 == 0)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61