gpt4 book ai didi

JavaScript 过滤器函数 : filter on multiple conditions (either could be true)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:55 24 4
gpt4 key购买 nike

可能是一些 super 简单的东西,我没仔细看。

我有一个包含一些信息的对象数组。根据用户操作,我想过滤掉一些对象;

let arr = [
{'num': 1, 'name': 'joe'},
{'num': 2, 'name': 'jane'},
{'num': 3, 'name': 'john'},
{'num': 3, 'name': 'johnny'},
]

我尝试过的

 function filterArr(arr) {
return arr.filter(obj => {
if(obj.num && obj.num !== 1) {
return obj;
}
if(obj.num && obj.num !== 3) {
return obj;
}
})
}

当我运行 filterArr 时,我返回了原始数组,但预期结果应该只是 {'num': 2, 'name': 'jane'},,。我可以在两个嵌套条件中使用 console.log。

任何基于 2 个条件中的 1 个为真过滤数组的帮助将不胜感激。

最佳答案

每个 num 都会通过 either 您的 if 条件,因为宇宙中没有等于 1 和同时 3 个**。您可以将 && 条件链接到 filter 中以检查所有条件:

let arr = [
{'num': 1, 'name': 'joe'},
{'num': 2, 'name': 'jane'},
{'num': 3, 'name': 'john'},
{'num': 3, 'name': 'johnny'},
]

let filtered = arr.filter(a => a.num && a.num !== 3 && a.num !== 1)

console.log(filtered)

(** 除非它是 0nullundefined 或任何 falsy 值当然。在这种情况下,它们将两个 ifs)

obj.num 条件均失败

关于JavaScript 过滤器函数 : filter on multiple conditions (either could be true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54485282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com