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

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

问题描述

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

  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元素!=='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天全站免登陆