基于索引数组过滤数组 [英] Filter array based on an array of index
问题描述
首先我道歉,如果它是重复的(我搜索但没有找到这个简单的例子......),但我想根据索引选择 arr1
的元素在 arr2
:
First I apologize if it's a duplicate (I searched but did not find this simple example...), but I want to select elements of arr1
based on the index in arr2
:
arr1 = [33,66,77,8,99]
arr2 = [2,0,3]
我正在使用 underscore.js
但未检索 0
索引(似乎被视为 false
):
I am using underscore.js
but the 0
index is not retrieved (seems to be considered as false
):
res = _.filter(arr1, function(value, index){
if(_.contains(arr2, index)){
return index;
}
});
返回:
# [77, 8]
我怎么能解决这个问题,并且在那里使用索引数组过滤的更简单方法?我期待以下结果:
How could I fix this, and is there a simpler way to filter using an array of indexes? I am expecting the following result:
# [77, 33, 8]
推荐答案
最简单的方法是使用 _。map
在 arr2
上,像这样
The simplest way is to use _.map
on arr2
, like this
console.log(_.map(arr2, function (item) {
return arr1[item];
}));
// [ 77, 33, 8 ]
在这里,我们迭代索引并获取来自 arr1
的相应值并创建一个新数组。
Here, we iterate the indexes and fetching the corresponding values from arr1
and creating a new array.
如果您的环境支持ECMA Script 6的Arrow功能,那么您只需执行
If your environment supports ECMA Script 6's Arrow functions, then you can simply do
console.log(_.map(arr2, (item) => arr1[item]));
// [ 77, 33, 8 ]
此外,您可以使用原生 Array.protoype.map
本身,如果您的目标环境支持它们,就像这样
Moreover, you can use the native Array.protoype.map
itself, if your target environment supports them, like this
console.log(arr2.map((item) => arr1[item]));
// [ 77, 33, 8 ]
这篇关于基于索引数组过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!