如何根据 JavaScript 中另一个数组的索引从数组中选择元素? [英] How to select elements from an array based on the indices of another array in JavaScript?

查看:18
本文介绍了如何根据 JavaScript 中另一个数组的索引从数组中选择元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有效,但我想知道是否有更好的方法来按索引过滤:

a = [10,20,30,40]b = [1,3]a.filter((x,i) => b.includes(i))//[20, 40]

解决方案

另一种方式是 b.map(aIndex => a[aIndex]).如果 ba 短,这也可能更快.但是,如果 b 中存在不属于 a 的索引,您将在数组中得到 undefined 的空洞".>

编辑

稍微研究一下 Array.includes,看起来它会在 O(n) 中运行,用于未排序的数组.如果我们说 A = a.lengthB = 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 中另一个数组的索引从数组中选择元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆