我想知道是否有一种精确的方法可以在 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
对于上面的 brewity,但过滤表达式可能比这更复杂。所以,我必须强调 问题的重点不是两个字符串数组的区别 .我要留下另一个例子,希望问题不会被合并: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)
最佳答案
如果您担心迭代两次 myArray
,您可能首先考虑降低计算复杂度。因为循环的每次迭代调用 Array.prototype.includes
,以及 Array.prototype.includes
的复杂度是 O(n)
,您的代码的总体复杂度为 O(n ^ 2)
. (外循环:O(n)
* 内循环:O(n)
)。所以,考虑先解决这个问题:使用 Set 和 Set.has
, 一个 O(1)
操作,而不是数组和 .includes
.这是假设您的实际 filterArray
足够大以至于计算复杂性值得担心 - 集合确实有一点开销成本。
至于问题的另一(主要)部分,一种选择是在外部创建两个结果数组,然后在迭代时推送到适当的数组:
const myArray = ['a', 'b', 'c', 'd', 'e']
const filterArray = new Set(['a', 'b'])
const filteredInResult = [];
const filteredOutResult = [];
for (const e of myArray) {
(filterArray.has(e) ? filteredInResult : filteredOutResult).push(e);
}
console.log(filteredInResult)
console.log(filteredOutResult)
也可以使用
reduce
,虽然我不认为它看起来很好:const myArray = ['a', 'b', 'c', 'd', 'e']
const filterArray = new Set(['a', 'b'])
const { filteredInResult, filteredOutResult } = myArray.reduce((a, e) => {
a[filterArray.has(e) ? 'filteredInResult' : 'filteredOutResult'].push(e);
return a;
}, { filteredInResult: [], filteredOutResult: [] });
console.log(filteredInResult)
console.log(filteredOutResult)
关于javascript - 如何在Javascript中一次性过滤进出数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59050741/