【发布时间】:2020-03-21 20:39:47
【问题描述】:
我想知道是否有一种精确的方法可以在 Javascript 中过滤数组中未过滤的元素,我的意思是,一次完成。
目前,我使用如下逻辑:
const myArray = ['a', 'b', 'c', 'd', 'e']
const filterArray = ['a', 'b']
// I want to combine those two expressions somehow
const filteredInResult = myArray.filter(e => filterArray.includes(e))
const filteredOutResult = myArray.filter(e => !filterArray.includes(e))
console.log(filteredInResult)
console.log(filteredOutResult)
我觉得可能已经有类似destructuring 的方式来实现它,但无论如何,我更喜欢问你们是否有一种方法可以一次性过滤出和过滤出结果。
编辑: 如果这个问题与问题here 相似,SO 会一直提醒我,但我使用字符串比较和includes 进行上述酿造,但过滤表达式可能比这更复杂.所以,我必须强调问题的重点不是两个字符串数组的差异。我要留下另一个例子,希望问题不会被合并:D
// A more complex use case
const myArray = [
{id: 1, value: 'a'},
{id: 2, value: 'b'},
{id: 3, value: 'c'},
{id: 4, value: 'd'},
{id: 5, value: 'e'},
]
const filterArray = ['a', 'b']
// I want to combine those two expressions somehow
const filteredInResult = myArray.filter(e => filterArray.includes(e.value))
const filteredOutResult = myArray.filter(e => !filterArray.includes(e.value))
console.log(filteredInResult)
console.log(filteredOutResult)
【问题讨论】:
-
意识到“一次性”是上下文相关的。在答案和问题示例中,“包含”的使用是对表达循环的每次迭代进行查找(内部循环)。在任何情况下都不会有“一次性”解决方案。
-
@JuhilSomaiya 不,我编辑并添加了另一个用例,以表明结构相似的数组并不总是差异。
标签: javascript arrays filter