Array.prototype.filter automatically filters out false
Does the filter function automatically filter out false values ββsuch as false, null or undefined? If so, how to stop it from doing it.
I need to filter out all 0s in an array, so I used the array.filter callback and realized that the filter function removes false values ββeven when I want to store them. Is there a way to get around this?
EDIT: This is the code I have and the deep comparison did not return false.
function removeZero(arr) {
return arr.filter(function(element){
if(element!==0){
return element;
}
});
}
EDIT 2: Here's a repl.it link containing the contents of the test array, and when I ran it, the result filters out the values ββfalse, null and undefined. https://repl.it/BAiK
source to share
Use operator !==
[1,2,3,0,[],{},false,undefined].filter(function(e){return e !== 0})
// Output: [1, 2, 3, Array[0], Object, false, undefined]
compare to operator output !=
(which you don't want to use)
[1,2,3,0,[],{},false,undefined].filter(function(e){return e != 0})
// Output: [1, 2, 3, Object, undefined]
This is the code you provided https://repl.it/BAiK
var removeZeros = function (arr) {
return arr.filter(function(element){
if(element!==0){
return element; // here is the error, you need to return a boolean. (true to add element to final array, false to ignore element)
}
});
}
console.log(removeZeros([false, 1, 2, 3, null, 0, 4, undefined, 5, 0]));
// Output: [ 1, 2, 3, 4, 5 ]
You see, the return value for the filter function should be a boolean value, not the item you want to return. When you return false the item is not added to the final array, when you return true the item being processed is returned. See my edit with the corrected code.
This is your code that has been fixed.
var removeZeros = function (arr) {
return arr.filter(function(element){
return element !== 0 // this returns a boolean
});
}
console.log(removeZeros([false, 1, 2, 3, null, 0, 4, undefined, 5, 0]));
// Output: [ false, 1, 2, 3, null, 4, undefined, 5 ]
source to share
var result = [1, 2, 3, 0, false, undefined, null, -1].filter(
function (e) {
return e !== 0;
});
document.getElementById('out').innerHTML = result.reduce(function (r, a) { return r + '\n ' + a + ' [' + (typeof a) + ']'; }, '[') + '\n]';
<pre id="out"></pre>
your example does not return true but the itselft value being evaluated. Array.filter()
includes the element if the return value is true.
function removeZero(arr) {
return arr.filter(function(element) {
if (element !== 0){
return element; // <-- falsy values are not true.
}
});
}
source to share