问题描述
这有效,但我想知道是否有更好的方法来按索引过滤:
a = [10,20,30,40]b = [1,3]a.filter((x,i) => b.includes(i))//[20, 40]
另一种方式是 b.map(aIndex => a[aIndex])
.如果 b
比 a
短,这也可能更快.但是,如果 b
中存在不属于 a
的索引,您将在数组中得到 undefined
的空洞".>
编辑
稍微研究一下 Array.includes
,看起来它会在 O(n) 中运行,用于未排序的数组.如果我们说 A = a.length
和 B = b.length
,那么您的问题解决方案应该在 O(A * B) 中运行.第二个解决方案(带地图)将在 O(B) 中运行.要修复 undefined
漏洞,您可以添加一个 .filter(element => typeof element !== 'undefined')
.最终的解决方案将是 b.map(i => a[i]).filter(e => typeof e !== 'undefined')
.这现在在 O(2 * B) 中运行,这应该仍然比 O(A * B) 好.
This works, but I'm wondering if there is a better way to filter by index:
a = [10,20,30,40]
b = [1,3]
a.filter((x,i) => b.includes(i))
// [20, 40]
Another way would be b.map(aIndex => a[aIndex])
. If b
is shorter than a
this could also be faster. However if there are indexes in b
that do not belong in a
, you would end up with undefined
"holes" in the array.
EDIT
Looking a bit into Array.includes
, looks like it will run in O(n) for unsorted arrays.If we say A = a.length
and B = b.length
, your solution from the question should run in O(A * B).The second solution (with map) will run in O(B). To fix the undefined
holes, you could add a .filter(element => typeof element !== 'undefined')
.The final solution would then be b.map(i => a[i]).filter(e => typeof e !== 'undefined')
. This now runs in O(2 * B), which should still be better than O(A * B).
这篇关于如何根据 JavaScript 中另一个数组的索引从数组中选择元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!