Remove all falsy values from an array
JavascriptArraysJavascript Problem Overview
I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.
function bouncer(arr) {
arr = arr.filter(function (n) {
return (n !== undefined && n !== null && n !== false && n !== 0 && n !== "" && isNaN()!=NaN); });
return arr;
}
bouncer([7, "ate", "", false, 9, NaN], "");
The above is getting satisfied for all except the NaN test case. Can someone help me check in the array whether it contains NaN or not?
Javascript Solutions
Solution 1 - Javascript
You can use Boolean :
var myFilterArray = myArray.filter(Boolean);
Solution 2 - Javascript
Since you want to get rid of "falsy" values, just let JavaScript do its thing:
function bouncer(arr) {
return arr.filter(function(v) { return !!v; });
}
The double-application of the !
operator will make the filter callback return true
when the value is "truthy" and false
when it's "falsy".
(Your code is calling isNaN()
but not passing it a value; that's why that test didn't work for you. The isNaN()
function returns true
if its parameter, when coerced to a number, is NaN
, and false
otherwise.)
edit — note that
function bouncer(arr) {
return arr.filter(Boolean);
}
would work too as LoremIpsum notes in another answer, because the built-in Boolean constructor does pretty much the exact same thing as !!
.
Solution 3 - Javascript
truthyArray = arr.filter(el => el)
^ that's how you do it
Solution 4 - Javascript
Solution 5 - Javascript
You use isNaN()
in wrong way. It should be something like following:
function bouncer(arr) {
return arr.filter(function (n) {
return n !== undefined && n !== null && n !== false && n !== 0 && n !== "" && !isNaN(n);
});
}
Also you can rewrite it:
function bouncer( arr ){
return arr.filter( function( value ){
return value;
});
}
Solution 6 - Javascript
Using filter we can write
function bouncer(arr) {
return arr.filter(item => item);
}
bouncer([false, null, 0, NaN, undefined, ""]) // will return [].
Solution 7 - Javascript
This is another equivalent, but illustrative, solution:
function bouncer( arr ){
return arr.filter( function( value ){
return value ? true : false;
});
}
This code sample is illustrative because it indicates to a reader that the variable value
will be evaluated as truthy or falsey, and the anonymous function will return a boolean, either true
or false
, mapping to the evaluation of value
.
For someone who is not familiar with this approach of removing values from an array based on their truthiness, or for someone who is not familiar with (or has not read the documentation on) the filter
function, this example is the most concise that still conveys the behavior of the filter
function.
Of course, in your application you may opt for the more concise, yet less insightful, implementation:
function bouncer( arr ){
return arr.filter( function( value ){
return value;
});
}
Solution 8 - Javascript
I know this can be done using the arr.filter() method. But I prefer using the Boolean() function. Is clearer to me. Here's how I did it, although a little longer:
function bouncer(arr) {
// Don't show a false ID to this bouncer.
var falsy;
var trueArr = [];
for (i = 0; i < arr.length; i++) {
falsy = Boolean(arr[i]);
if (falsy === true) {
trueArr.push(arr[i]);
}
}
return trueArr;
}
bouncer([7, "ate", "", false, 9]);
// returns a new array that is filtered accordingly.
Solution 9 - Javascript
I think a better deal this way
function bouncer(arr) {
arr = arr.filter(function(item) {
return item;
return arr;
bouncer([7, "ate", "", false, 9, NaN, undefined, 0]);
Solution 10 - Javascript
bouncer function:
function bouncer(arr) {
return arr.filter((val) => {
return !!val;
});
}
console.log(bouncer([7, "ate", "", false, 9]));
Solution 11 - Javascript
Thanks for all working answers above. Here are 3 approaches to solve the problem. Third solution addressed problem by your approach @Vignesh.
1.
function bouncer(arr) {
return arr.filter( function( val ){
return val;
});
}
2.
function bouncer(arr) {
return arr.filter(Boolean);
}
3.
function bouncer(arr) {
return arr.filter(function(val){
return val !== false && val !== "" && !(Number.isNaN(val)) && val !==
undefined && val !== 0 && val !== null;
});
}
Solution 12 - Javascript
Just negate twice to "cast" to boolean. !NaN === true
=> !!NaN === false
const truthy = arr.filter(o => !!o)
Solution 13 - Javascript
This is my idea...
function bouncer(arr) {
// Don't show a false ID to this bouncer.
var result = [];
function isGood(obj){
if(!Boolean(obj)){
return false;
} else {
return true;
}
}
for (var i=0; i < arr.length; i++){
if (isGood(arr[i]) === true){
result.push(arr[i]);
}
}
return result;
}
console.log(bouncer([7, "ate", "", false, 9]));
Solution 14 - Javascript
Try using filter and Boolean:
let array = [7,"ate","",false,9];
array.filter((values) => {return Boolean(values) === true })
Solution 15 - Javascript
If you like to use JS utility libraries like Lodash or Underscore.js you can use the compact
function.
import _ from 'lodash' // or import _ from 'underscore'
_.compact([0, 1, false, 'hello', '', {}, null]) // returns [1, 'hello', {}]
Documentation:
Solution 16 - Javascript
Use .filter
myArray.filter(val => Boolean(val));
Solution 17 - Javascript
function bouncer(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
result.push(arr[i]);
}
}
return result;
}
bouncer([7, "ate", "", false, 9]);
Solution 18 - Javascript
function falsy(value) {
if (value) {
return value;
}
}
function bouncer(arr) {
var filter = arr.filter(falsy);
return filter;
}
bouncer([7, "ate", "", false, 9]);
Solution 19 - Javascript
function removeFalsy(value){
var val = Boolean(value);
if(!val)
return false;
return true;
}
function bouncer(arr) {
return arr.filter(removeFalsy);
}
bouncer([7, "ate", "", false, 9]);
Solution 20 - Javascript
This should be what you are looking for:
let array = [7, 'ate', '', false, 9, NaN];
function removeFalsyItems(array) {
// Your result
let filter = array.filter(Boolean);
// Empty the array
array.splice(0, array.length);
// Push all items from the result to our array
Array.prototype.push.apply(array, filter);
return array
}
removeFalsyItems(array) // => [7, 'ate', 9], funny joke btw...
Solution 21 - Javascript
myArray = [false, null, 0, NaN, undefined, ""];
myArray.map(item => {
//if you want you can write logic
console.log(item);
})
// Get rid of bad values
.filter(Boolean);
it will return [].
Solution 22 - Javascript
I see you never accepted an answer. Is the problem that you are relying on Logger.log or console.log to see if the null removal worked? I think the filter suggested by @LoremIpsum is the cleanest solution.
const src2DArr = [[34], [75], [30], [48], [976], [], [178], [473], [51], [75], [29], [47], [40]];
Logger.log("src2DArr: " +JSON.stringify(src2DArr));
// [[34],[75],[30],[48],[976],[],[178],[473],[51],[75],[29],[47],[40]]
var src2DArr1 = src2DArr.filter(Boolean);
Logger.log("src2DArr1: " + JSON.stringify(src2DArr1));
// [[34],[75],[30],[48],[976],[],[178],[473],[51],[75],[29],[47],[40]]
Solution 23 - Javascript
Falsy values
- false
- zero(0,-0)
- empty string(“”, ‘ ‘ , ` `)
- BigIntZero(0,0x0n)
- null
- undefined
- NaN
const values = [false,'false','js', true, 0 , [],[1,2,3], 1, 'b', {},
'', NaN, undefined, null, -5,1n,0n,0x1n,0x0n];
console.log(values.filter((value)=> !!value));
console.log(values.filter((value) => value ));
console.log(values.filter((value)=> Boolean(value)));
console.log(values.filter(Boolean));
//=> [ 'false', 'js', true, [], [ 1, 2, 3 ], 1, 'b', {}, -5, 1n, 1n ]
// note: empty collections are not falsy like in python (empty array)
//note: will syntax error for 1x0n, 'false' is string here
const values = [false,'false','js', true, 0 , [],[1,2,3], 1, 'b', {}, '', NaN, undefined, null, -5,1n,0n,0x1n,0x0n];
//=> [ 'false', 'js', true, [], [ 1, 2, 3 ], 1, 'b', {}, -5, 1n, 1n ]
//=> [ 'false', 'js', true, [], [ 1, 2, 3 ], 1, 'b', {}, -5, null, null ] // BigInt not supported compilers
// double not
// first not makes it as boolean opposite values, then second not give its inversion
console.log(values.filter(
(value)=> !!value
));
// Auto Coercion
// values are self identified as falsy or not
console.log(values.filter(
value => value
));
// Boolean type conversion
// get values as parem and return boolean as falsy or not
console.log(values.filter(
(value)=> Boolean(value)
));
// Boolean constructor
// This works because Boolean itself is a function, and the arguments filter supplies are passed directly to it
console.log(values.filter(
Boolean
));
For Detailed explanation refer : samanthaming website
Solution 24 - Javascript
function bouncer(arr) {
function filterFalse(value) {
var a = Boolean(value);
if (a === true) {
return a;
}
return a;
}
function filterArray(x) {
var y = filterFalse(x);
if (y) {
return true;
} else {
return false;
}
}
var newArr = arr.filter(filterArray);
return newArr;
}
bouncer([1, null, NaN, 2, undefined]);
Solution 25 - Javascript
removing false values from array with ECMAscript 5 Vanila JS
function bouncer(arr){
let trueArray = [];
for(int i=0; i<arr.lenght; i++){
if(arr[i]===true){
trueArray.push(arr[i]);
}
}
return trueArray;
}
removing false values from array using ECMAscript6 or Ecma2015 method
function bouncer(arr){
let trueArray = arr.filter( item => item===true);
return trueArray;
}