Reputation: 170
My goal was to determine if an array contained any falsey elements and create a new array without those elements. I came up with a HORRIBLY ugly function but i just couldnt figure out a better way to write it.
function bouncer(arr) {
var newArray = [];
for (var i = 0; i < arr.length; i++)
if (arr[i] !== false ) {
if (arr[i] !== NaN) {
if (arr[i] !== "") {
if (arr[i] !== 0) {
if (arr[i] !== undefined) {
if (arr[i] !== null) {
newArray.push(arr[i]);
}}}}}}
return newArray;
}
bouncer([7, 'ate', '', false, 9]);
I tried using an if statement using miltiple conditions like
if (arr[i] !== false || arr[i] !== "")
But when I did that it wouldnt catch both conditions for some reason. what would have been a simpler way to do this ?
Upvotes: 3
Views: 362
Reputation: 386848
Check if arr[i]
is truthy and then push the value.
arr[i] && newArray.push(arr[i]);
Complete code:
function bouncer(arr) {
var newArray = [], i;
for (i = 0; i < arr.length; i++) {
arr[i] && newArray.push(arr[i]);
}
return newArray;
}
Or with Array.filter
:
newArr = arr.filter(function (a) { return a; });
Upvotes: 1
Reputation: 5708
A more readable version of @Nina Scholz's answer would be to explicitly check for truthiness without relying on short circuiting.
if (arr[i]) { newArray.push(arr[i]); }
Of course for your situation, you could use filter
newArr = arr.filter(function(el){ return el == true; });
Upvotes: 1
Reputation: 61
You should use filter.
var arr1 = [0, 1, false, '', 'zero', null];
var arr2 = arr1.filter(function (item) {
return !!item;
});
console.log(arr2); // [1, 'zero']
Documentation for filter can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Upvotes: 0
Reputation: 21789
You are using OR, should use AND instead:
if (arr[i] !== false && arr[i] !== "")
Upvotes: 1