基于索引数组过滤数组

Col*_*vel 5 javascript arrays underscore.js

首先我道歉,如果它是重复的(我搜索但没有找到这个简单的例子......),但我想选择arr1基于索引的元素arr2:

arr1 = [33,66,77,8,99]
arr2 = [2,0,3] 
Run Code Online (Sandbox Code Playgroud)

我正在使用underscore.js0索引未被检索(似乎被视为false):

res = _.filter(arr1, function(value, index){
    if(_.contains(arr2, index)){
        return index;
    }
});
Run Code Online (Sandbox Code Playgroud)

哪个回报:

# [77, 8]
Run Code Online (Sandbox Code Playgroud)

我怎么能解决这个问题,是否有更简单的方法来过滤使用索引数组?我期待以下结果:

# [77, 33, 8]
Run Code Online (Sandbox Code Playgroud)

the*_*eye 7

最简单的方法是使用_.mapon arr2,就像这样

console.log(_.map(arr2, function (item) {
  return arr1[item];
}));
// [ 77, 33, 8 ]
Run Code Online (Sandbox Code Playgroud)

在这里,我们迭代索引并从中获取相应的值arr1并创建新数组.


如果您的环境支持ECMA Script 6的Arrow功能,那么您可以这样做

console.log(_.map(arr2, (item) => arr1[item]));
// [ 77, 33, 8 ]
Run Code Online (Sandbox Code Playgroud)

此外,Array.protoype.map如果您的目标环境支持它们,您可以使用本机本身,就像这样

console.log(arr2.map((item) => arr1[item]));
// [ 77, 33, 8 ]
Run Code Online (Sandbox Code Playgroud)


小智 5

对我来说,最好的方法是使用filter

let z=[10,11,12,13,14,15,16,17,18,19]

let x=[0,3,7]

z.filter((el,i)=>x.some(j => i === j))
//result
[10, 13, 17]
Run Code Online (Sandbox Code Playgroud)