简体   繁体   English

从数组中删除所有虚假值

[英]Remove all falsy values from an array

I would like to remove all falsy values from an array.我想从数组中删除所有虚假值。 Falsy values in JavaScript are false, null, 0, "", undefined, and NaN. JavaScript 中的 Falsy 值为 false、null、0、""、undefined 和 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.除了 NaN 测试用例之外,以上所有内容都得到了满足。 Can someone help me check in the array whether it contains NaN or not?有人可以帮我检查数组是否包含 NaN 吗?

您可以使用布尔值:

var myFilterArray = myArray.filter(Boolean);

Since you want to get rid of "falsy" values, just let JavaScript do its thing:既然你想摆脱“虚假”值,就让 JavaScript 做它的事情:

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".运算符将使过滤器回调在值为“真”时返回true ,在值为“ false ”时返回假。

(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.) (您的代码正在调用isNaN()但未向其传递值;这就是该测试对您不起作用的原因。 isNaN()函数在其参数强制为数字时NaN true ,否则返回false 。 )

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 !!正如 LoremIpsum 在另一个答案中所指出的那样,它也可以工作,因为内置的布尔构造函数与!! . .

truthyArray = arr.filter(el => el)

^ 你就是这样做的

Using this simple filter will do:使用这个简单的过滤器可以:

array.filter(Boolean)

You can read more about Boolean here您可以在此处阅读有关Boolean的更多信息

You use isNaN() in wrong way.您以错误的方式使用isNaN() 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;
    });
}

Using filter we can write使用过滤器我们可以写

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

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 .此代码示例是说明性的,因为它向读者表明变量value将被评估为真或假,并且匿名函数将返回一个布尔值,无论是true还是false ,映射到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.对于不熟悉这种根据真实性从数组中删除值的方法的人,或者对于不熟悉(或未阅读有关) filter函数的文档的人,这个例子是最简洁的,仍然传达filter函数的行为。

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.我知道这可以使用 arr.filter() 方法来完成。 But I prefer using the Boolean() function.但我更喜欢使用 Boolean() 函数。 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.

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

bouncer function:保镖功能:

 function bouncer(arr) { return arr.filter((val) => { return !!val; }); } console.log(bouncer([7, "ate", "", false, 9]));

Thanks for all working answers above.感谢以上所有有效的答案。 Here are 3 approaches to solve the problem.这里有3种方法来解决这个问题。 Third solution addressed problem by your approach @Vignesh.第三个解决方案通过您的方法@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;
    });
 }

Just negate twice to "cast" to boolean.只需两次否定即可“转换”为布尔值。 !NaN === true => !!NaN === false !NaN === true => !!NaN === false

    const truthy = arr.filter(o => !!o)

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

Try using filter and Boolean:尝试使用过滤器和布尔值:

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

If you like to use JS utility libraries like Lodash or Underscore.js you can use the compact function.如果你喜欢使用像LodashUnderscore.js这样的 JS 实用程序库,你可以使用compact函数。

import _ from 'lodash' // or import _ from 'underscore'

_.compact([0, 1, false, 'hello', '', {}, null]) // returns [1, 'hello', {}]

Documentation:文档:

使用.filter

myArray.filter(val => Boolean(val));
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]);
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]);

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...
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?您是否依赖 Logger.log 或 console.log 来查看 null 删除是否有效? I think the filter suggested by @LoremIpsum is the cleanest solution.我认为@LoremIpsum 建议的过滤器是最干净的解决方案。

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

Falsy values虚假值

  • false错误的
  • zero(0,-0)零(0,-0)
  • empty string(“”, ' ' , ` `)空字符串(“”, ' ' , ` `)
  • BigIntZero(0,0x0n) 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详细解释请参考: samanthaming website

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

lodash can do the trick nicely, there is a _.compact() function. lodash可以很好地完成技巧,其中有一个_.compact()函数。

 const arr = [7, "ate", "", false, 9, NaN]; console.log(_.compact(arr)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script> 

removing false values from array with ECMAscript 5 Vanila JS使用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使用ECMAscript6Ecma2015方法从数组中删除错误值

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
}
function bouncer(arr) {

// Don't show a false ID to this bouncer.

for (var i = 0; i < arr.length; i++) {
        if (!arr[i]) {
            arr.splice(i, 1);
            i = i-1;
        }
    }
    return arr;

}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM