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);
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?
Share Improve this question edited Feb 22, 2023 at 8:04 Tomerikoo 19.4k16 gold badges54 silver badges67 bronze badges asked Aug 16, 2018 at 11:48 newcasionewcasio 2531 gold badge7 silver badges17 bronze badges 3- 3 This is not how Array.filter works. The callback needs to return a boolean. – Jeto Commented Aug 16, 2018 at 11:49
- 1 You want to return true rather than x – eddiewould Commented Aug 16, 2018 at 11:49
- Possible duplicate of Understanding JavaScript Truthy and Falsy – str Commented Aug 16, 2018 at 11:50
6 Answers
Reset to default 8You 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);
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.
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.
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);
const myEvennessFilter = (args) => args.filter(elem => (elem % 2) === 0);
console.log(myEvennessFilter([1,2,3,4,5,6,7,8,9]));
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)