英文:
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 < 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;
}
答案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 => 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, {}, "0", 5, Infinity, "hello", [], false, -1]
const y = x.filter(e => !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 => !val)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论