返回一个新数组,其中删除了所有真值。

huangapple go评论62阅读模式
英文:

How to return a new array with all truthy values removed? (Javascript)

问题

以下是要翻译的内容:

我已经知道如何从数组中移除假值,但还没有找到一个返回一个新数组,其中所有真值元素都被移除的解决方案。我尝试用真值替换假值在我的“解决方案”中,但结果并没有给我留下一个只包含假值的数组。

var removeTruthy = function (arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == true || (arr[i]) == {} || arr[i] == "0" || arr[i] == 5 || arr[i] == Infinity || arr[i] == "hello") {
            arr.splice(i, 1);
            i--;
        }
    }
    return arr;
}
英文:

I have seen how to remove falsy values from an array but haven't found a solution for returning a new array with all truthy elements removed. I attempted to replace falsy values with truthy ones in my "solution" but the results are not leaving me with an array with only falsy values.

      var removeTruthy = function (arr) {
         
          for (var i = 0; i &lt; arr.length; i++) {
       
          if (arr[i] == true  || (arr[i]) == {} || arr[i] == &quot;0&quot; || arr[i] == 5 || arr[i] == Infinity      || arr[i] == &quot;hello&quot;) {
              arr.splice(i, 1);
             i--;
         }
        
     }
     return arr;
 }
  



答案1

得分: 0

All you need is .filter().

To filter out all the falsy, .filter(element => element).

To filter out all the truthy, this:

const x = [null, 0, 1, 2, 3, undefined, true, {}, "0", 5, Infinity, "hello", [], false, -1]

const y = x.filter(e => !e)

console.log(y)
英文:

All you need is .filter()

To filter out all the falsy, .filter(element =&gt; element).

To filter out all the truthy, this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const x = [null, 0, 1, 2, 3, undefined, true, {}, &quot;0&quot;, 5, Infinity, &quot;hello&quot;, [], false, -1]

const y = x.filter(e =&gt; !e)

console.log(y)

<!-- end snippet -->

答案2

得分: 0

// 移除真值
var removeTruthy = function (arr) {
return arr.filter(val => !val)
}

英文:
// remove truthy values
var removeTruthy = function (arr) {
    return arr.filter(val =&gt; !val)
}

huangapple
  • 本文由 发表于 2023年4月7日 01:15:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定