首先,如果它是重复的,我深表歉意(我搜索过但没有找到这个简单的例子......),但我想根据 arr2< 中的索引选择
:arr1
的元素
arr1 = [33,66,77,8,99]
arr2 = [2,0,3]
我正在使用 underscore.js
但未检索到 0
索引(似乎被认为是 false
):
res = _.filter(arr1, function(value, index){
if(_.contains(arr2, index)){
return index;
}
});
哪个返回:
# [77, 8]
我该如何解决这个问题,是否有更简单的方法来使用索引数组进行过滤?我期待以下结果:
# [77, 33, 8]
最佳答案
最简单的方法是在arr2
上使用_.map
,像这样
console.log(_.map(arr2, function (item) {
return arr1[item];
}));
// [ 77, 33, 8 ]
在这里,我们迭代索引并从 arr1
中获取相应的值并创建一个新数组。
与上述等价,但也许更高级一点,是使用 _.propertyOf
而不是匿名函数:
console.log(_.map(arr2, _.propertyOf(arr1)));
// [ 77, 33, 8 ]
如果你的环境支持 ECMA Script 6 的 Arrow 函数,那么你也可以这样做
console.log(_.map(arr2, (item) => arr1[item]));
// [ 77, 33, 8 ]
此外,如果您的目标环境支持它们,您可以使用 native Array.protoype.map
本身,就像这样
console.log(arr2.map((item) => arr1[item]));
// [ 77, 33, 8 ]
关于javascript - 基于索引数组过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33211799/