这有效,但我想知道是否有更好的方法来过滤索引:
a = [10,20,30,40]
b = [1,3]
a.filter((x,i) => b.includes(i))
// [20, 40]
Run Code Online (Sandbox Code Playgroud)
另一种方式是b.map(aIndex => a[aIndex]).如果b比a这短,也可以更快.但是,如果存在b不属于的索引,则a最终会undefined在数组中出现"漏洞".
编辑
看一下Array.includes,看起来它会在O(n)中运行未排序的数组.如果我们说,A = a.length并且B = b.length问题的解决方案应该在O(A*B)中运行.第二个解决方案(带有map)将在O(B)中运行 .要修复这些undefined洞,你可以添加一个.filter(element => typeof element !== 'undefined').那么最终的解决方案就是b.map(i => a[i]).filter(e => typeof e !== 'undefined').现在运行在O(2*B),这应该仍然优于O(A*B).