基于索引数组筛选数组

Filter array based on an array of index

本文关键字:数组 筛选 索引 于索引      更新时间:2023-09-26

首先,如果它是重复的,我道歉(我搜索了,但没有找到这个简单的例子…),但我想根据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 ]

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

console.log(arr2.map((item) => arr1[item]));
// [ 77, 33, 8 ]

对我来说,最好的方法是使用过滤器

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]

可以对想要子集的数组使用filter方法。filter遍历数组并返回一个由通过测试的项组成的新数组。测试是一个回调函数,在下面的示例中是一个匿名箭头函数,它接受必需的currentValue和可选的index参数。在下面的例子中,我使用_作为第一个参数,因为它没有被使用,这样linter就不会将其突出显示为未使用:)。
在回调函数中,数组的includes方法用于作为索引源的数组,以检查arr1的当前索引是否属于所需索引的一部分。

let arr1 = [33, 66, 77, 8, 99];
let arr2 = [2, 0, 3];
let output = arr1.filter((_, index) => arr2.includes(index));
console.log("output", output);

您返回的是index,因此在您的情况下,0被视为false。所以你需要返回true而不是

res = _.filter(arr1, function(value, index){
    if(_.contains(arr2, index)){
        return true;
    }
});

或者只返回_.contains()

res = _.filter(arr1, function(value, index){
   return _.contains(arr2, index);
});

_.contains返回布尔值。您应该从filter谓词返回该值,而不是从索引返回,因为0是一个假值。

res = _.filter(arr1, function(value, index)) {
  return _.contains(arr2, index);
});
作为题外话,JavaScript数组有一个本地的filter方法,所以您可以使用:
res = arr1.filter(function(value, index)) {
  return _.contains(arr2, index);
});

通过索引数组迭代作为主循环是不是更好?

var arr1 = [33,66,77,8,99]
var arr2 = [2,0,3] 
var result = [];
for(var i=0; i<arr2.length; i++) {
   var index = arr2[i];
   result.push(arr1[index]);
}
console.log(result);