从数组中删除所有虚假值

我希望从数组中删除所有虚假值。JavaScript 中的假值为 false、 null、0、“”、 unDefinition 和 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], "");

除了 NaN 测试用例之外,上面的内容都得到了满足。谁能帮我检查一下这个数组是否包含 NaN?

59703 次浏览

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 !!.

You can use Boolean :

var myFilterArray = myArray.filter(Boolean);

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;
});
}

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;
});
}

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.
truthyArray = arr.filter(el => el)

^ that's how you do it

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]);
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]);
function falsy(value) {
if (value) {
return value;
}
}


function bouncer(arr) {
var filter = arr.filter(falsy);
return filter;
}


bouncer([7, "ate", "", false, 9]);

bouncer function:

function bouncer(arr) {
return arr.filter((val) => {
return !!val;
});
}


console.log(bouncer([7, "ate", "", false, 9]));

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]);

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;
});
}
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]);

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]));

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...

Using filter we can write

function bouncer(arr) {
return arr.filter(item => item);
}
bouncer([false, null, 0, NaN, undefined, ""]) // will return [].

Try using filter and Boolean:

let array = [7,"ate","",false,9];
array.filter((values) => {return Boolean(values) === true })

Using this simple filter will do:

array.filter(Boolean)

You can read more about Boolean here

Just negate twice to "cast" to boolean. !NaN === true => !!NaN === false

    const truthy = arr.filter(o => !!o)
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 [].

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]]

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:

Use .filter

myArray.filter(val => Boolean(val));

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

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;
}
function compact(ar) {
let newArr = []
for (let i = 0; i < ar.length; i++) {
if (
!(
ar[i] === false ||
ar[i] === null ||
ar[i] === 0 ||
ar[i] === '' ||
ar[i] === undefined ||
(typeof ar[i] == 'number' && !ar[i])
)
) {
newArr.push(ar[i])
}
}
return newArr
}